April 08, 2025

Constructor and Destructor

 Constructor and Destructor

● A class constructor is a special member function of a class that is executed whenever we

create new objects of that class.

● A constructor will have exact same name as the class and it does not have any return type

at all, not even void.

● Constructors can be very useful for setting initial values for certain member variables.

There are three types of constructor in c++. They are:

1. Default Constructor.

2. Parametrized Constructor.

3. Copy Constructor.

Default constructor

Default constructor is the constructor which doesn't take any argument. It has no parameter.

Syntax:

class_name ()

{

//constructor definition

}

Example:

int main(){

Cube c;

cout<<c.side;

}class Cube

{

public:

int side;

Cube()

{

side=10;

}

};

Output: 10




Parameterized constructor

These are the constructors with parameter. Using this Constructor you can provide different

values to data members of different objects, by passing the appropriate values as argument.

Syntax:

Class_name (arg1,arg2,…)

{

//constructor code

}

Example:

#include<iostream.h>

#include<conio.h>

class Cube{

public:

int side;

Cube(int x)

{

side=x;

}

};

int main()

{

Cube c1(10);

Cube c2(20);

Cube c3(30);

cout<<c1.side;

cout<<c2.side;

cout<<c3.side;

}

Output:

10

20

30



Copy Constructor

These are special type of Constructors which takes an object as argument, and is used to copy

values of data members of one object into other object.

Syntax:

class_name (class_name &ref)

{

//code

}

Example:

#include<iostream.h>

#include<conio.h>

class A{

int a,b;

public:

A(int x, int y)

{

a=x;

b=y;

}

A(A &ref) //copy constructor

{

a=ref.a;

b=ref.b;

}

void show()

{

Cout<<a<<” ”<<b<<endl;

}

};

void main()

{

A obj1(10,20);

A obj2=obj1;

obj1.show();

obj2.show();

getch();

}



Destructor

● Destructor is used to destroy the object that have been created by a constructor .

● Destructor can never take any argument and it does not return any value.

● Invoked implicitly by the program to cleanup the storage.

Syntax:

~ destructor_name()

{

}

Example:

#include<iostream.h>

#include<conio.h>

int count=0;

class alpha{

public:

alpha(){

count++;

cout<<”no of object created”<<count;

}

~alpaha(){

cout<<”no of object destroyed”<<count;

count--;

}

};

void main()

{

alpha A1,A2,A3;

}


No comments:

Recent Posts

Oracle 19c Installation guide (Linux/ Windows)

Most Viewed Posts