Professional Documents
Culture Documents
Chapter 4 Object Constructions and Destructions
Chapter 4 Object Constructions and Destructions
While defining a constructor you must remember that the name of constructor will
be same as the name of the class, and constructors will never have a return type.
Constructors can be defined either inside the class definition or outside
class definition using class name and scope resolution :: operator.
class A
{
public:
int i;
A(); // constructor declared
};
// constructor definition
A::A()
{
i = 1;
}
Example of constructor
#include<iostream>
using namespace std;
class constructor
{
int a, b;
public:
constructor()
{
a=3;
b=2;
}
void display()
{
cout<<"a= "<<a<<endl;
cout<<"b= "<<b<<endl;
}
};
main()
{
constructor obj;
obj.display();
}
Output:
a= 3
b= 2
Another Example
How constructor works? Class Note (handwritten)
Use of constructor
How constructor are different from a normal member function?
Parameterized Constructor