Constructor In C++
- Constructor is a 'special' member function.
- Class name and function name are same.
- Constructor cannot be virtual.
- An object with a constructor cannot be used as a member of a union.
- It is automatically called when objects is created for the class.
Types Of Constructor
- Default constructor- no argument. Ex:book()
- Parameterized constructor – takes argument Ex: book(10, c++)
- Copy constructor- takes objects as argument Ex: book(book &obj)
Advantage
- Using a constructor Objects are automatically initialized when they are declared.
- There are numerous methods for initializing objects based on the number of arguments passed during the declaration.
- The base class's constructors can be used to initialize child class objects.
Program:
#include<iostream.h>
#include<string.h>
class book
{
private:
int bookno;
char bookname[20];
{
private:
int bookno;
char bookname[20];
public:
book( )
{
bookno=10;
Strcpy(bookname,"programming in C++");
}
~book( )
{
cout<<"destructor called";
}
void showdetails( )
{
cout<<"book no:"<<bookno<<endl;
cout<<"bookname:"<<bookname<<endl;
}
};
void main( )
{
book b1;
b1.showdetails( );
}
book( )
{
bookno=10;
Strcpy(bookname,"programming in C++");
}
~book( )
{
cout<<"destructor called";
}
void showdetails( )
{
cout<<"book no:"<<bookno<<endl;
cout<<"bookname:"<<bookname<<endl;
}
};
void main( )
{
book b1;
b1.showdetails( );
}