Constructors in C++

What is a Constructor…???It is a method which have it’s name same as it’s respective class name.In this tutorial we shall learn about constructors in detail.

The main properties of constructors are:
1.Name of the constructor is same as class name.
2.They don’t have any return type….even void too.
3.Constructor are invoked implicitly whenever an object is created.

They are two types of constructors in C++.
1.default constructor.
2.parameterized constructor.

A constructor which do not have any parameters is called as default constructor.
A constructor which takes one or more parameters is called as parameterized constructor.
Let us write a simple code to demonstrate the use of constructors in programming.

#include<iostream.h>
#include<conio.h>
class cont_demo
{
  public:
  cont_demo();      //default constructor
  cont_demo(int ); //parameterized constructor
}
cont_demo :: cont_demo()
{
  cout<<"\n\n\t\t   *****DEFAULT CONSTRUCTOR IS INVOKED*****";
}
cont_demo :: cont_demo(int i)
{
  cout<<"\n\n\t\t*****PARAMETERIZED CONSTRUCTOR IS INVOKED*****";
}
void main()
{
   clrscr();
   cont_demo ob;
   cont_demo ob1(1);
   getch();
}

But the above program is also an example of method overloading…i.e using the same name for two or more methods with a difference in number of parameters.
OUTPUT:
const_demo
You can download the program:download

Advertisements

About Anuroop D

Very enthusiastic about technology and likes to share my knowledge through blogging. Has Bachelor's in Information Technology and currently pursuing my Master's in Computer Science.
This entry was posted in C++ and tagged , , , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s