Constructors and its types in C++


Constructor

  • A constructor is used for automatic declaration of an object.
  • It has same name as the name of class in which it resides.
  • Constructor has no return type, even void.
  • If we have not define any constructor then C++ will automatically define it.
  • It is used only for initialization and not for input/output.

Syntax :

class class-name
{
private :

data member;

public :

class-name() //constructor defined
}
};

main()
{

class-name object=class-name(); //calling constructor
}


Example :



#include <iostream.h>
#include <conio.h>

class Account
{
private:

int account_no;
char *name;

public :

//defining the constructor Note that class-name and constructor name is same :

Account(char *n,int a)
{
//initializing the variables :

name=n;
account_no=a;
}

void display()
{
cout<< "Name is : "<< name;
cout<< "\nAccount number is : "<< account_no;

}

};

void main()
{
clrscr();

//creating object and calling the constructor :

Account acc=Account("Ashish",111);
acc.display();

getch();

}


Output :









Properties of constructors :

  • Constructors not have any return type, even void.
  • The constructor can't be virtual.
  • The constructor can't be static.
  • The name of the constructor is same as that of class.
  • Member function can be accessed within a constructor function.
  • A constructor initializes all the objects created under class.

Types of Constructors :

There are four types of constructors :

  • Default constructor
  • Parameterized constructor
  • Copy constructor
  • Dynamic constructor
We will discuss these types in the next topics.

1 comments:

Mundeku Technologies said...

Thanks.The notes are detailed.Alternatively visit www.georgemanyasa.kbo.co.ke

Post a Comment