Constructors and its types, Destructors | OOP in C++


Constructor


A constructor is a special member function whose name is same as class name, and it is used to perform those tasks that are required at the time of object creation. A constructor of a class is automatically called at the time of object creation.
A constructor that accepts no parameter is called Default Constructor. If no such constructor is defined, compiler supplies it.

Characteristics of constructor function:
1. They should be declared in public section.
2. They are invoked automatically when objects are created.
3. They do not have return type, even not void.
4. They can not be inherited, though a derived class can call the base class constructor.
5. Constructor can have default arguments.
6. Constructor cannot be virtual.
7. We cannot refer to their address.
8. They make implicit call to operators new and delete.
9. Constructor can also be defined inline.
10. Class of a constructor cannot be passed as a parameter to constructor. However, a constructor can accept reference to its own class as parameter. In such case, constructor is called the copy constructor.


#include<iostream.h>
class abc
{
int x, y;
public:
abc()
{
x=100;
}
void display(void)
{
cout<<"\nX"<<x<<"\nY="<<y;
}
};
int main()
{
abc t;
t.display();
}
Output
X=100
Y=7926


-Multiple Constructor, Parameterized Constructor and Constructor Overloading
-Passing objects to a function and returning objects from a function


#include<iostream.h>
class complex
{
float x, y;
public:
complex(){} //constructor no argument
complex(float a) //constructor with argument
{
x=y=a;
}
complex(float real, float imag) //constructor with two arguments
{x=real; y=imag;}
friend complex sum(complex, complex);
friend void display(complex);
};
complex sum(complex c1, complex c2)
{
complex c3;
c3.x=c1.x+c2.x;
c3.x=c1.y+c2.y;
return c3;
}
void display(complex c)
{
cout<<c.x<<"+j"<<c.y<<"\n";
}
int main(){
complex A(1.5,2.5);
complex B(3.2);
complex C;
C=sum(A, B) //friend function is called like normal c++ function.
cout<<"A="; display(A);
cout<<"B="; display(B);

cout<<"C="; display(C);
}


Copy Constructor


A copy constructor takes a reference to an object of the same class as itself as an argument.
class code
{
int id;
public:
code(){}
copy(int x){id=x;}
code(code &y)
{id=y.id;}
void show(void)
{
cout<<id;
}};
int main()
{
code A(100);
code B(A); // copy constructor called
cout<<"\n A="; A. show();
cout<<"\nB="; B.show();
}


Destructors


A Destructor is used to destroy the object. Destructors name is same as class name but preceded by tilde.
#include<iostream.h>
int count=0;
class myclass
{
public:
myclass()
{
count++;
cout<<"\n Objects Created="<<count;
}
~myclass()
{
Count--; cout<<"\n objects destroyed"<<count; }
}};
Int main()
{
cout<<"\n In block 1"; myclass e;
}
{cout<<"\n In block 2"; myclass f;
}
cout<<"\n Back in main()";
return 0;
}
Output:

.............

Custom Search

%d bloggers like this: