Advertisement



< Prev
Next >



C++ Constructor





In C++, a constructor is a special member function of a class, which is used to create and initialize the objects of its class. Each object of a class will have its own data members and access to the functions of its class.

Some important features of a constructor are -






A copy constructor is used to copy the value of one object into another object.

An example of a copy constructor-
//C++ An example of copy constructor


#include<iostream>

using namespace std;

class A
{
private:
int a,b;

public:
A(int x, int y)		//A simple constructor
{
	a = x;
	b = y;
}

A( A & ob)		//A copy constructor
{
	a = ob.a;
	b = ob.b;
}

void show_ab()
{
	cout<< "The value of a is : "<< a << "\n";
	cout<< "The value of b is : "<< b <<  "\n";
}
};


int main()
{
	//Calling the simple constructor
	A ob1(2,4);	
	
	cout<< "The value of data member a and b of the first object:" <<"\n";
	ob1.show_ab();

	//Calling the copy constructor to copy the values of ob1 to ob2
	A ob2(ob1);
	
	cout<< "The value of data member a and b of the second object:" << "\n";
	ob2.show_ab();
}


Output-


The value of data member a and b of the first object:
The value of a is : 2
The value of b is : 4
The value of data member a and b of the second object:
The value of a is : 2
The value of b is : 4






Please share this article -





< Prev
Next >
< Function Overriding
Destructor in C++ >



Advertisement

Please Subscribe

Please subscribe to our social media channels for daily updates.


Decodejava Facebook Page  DecodeJava Twitter Page Decodejava Google+ Page




Advertisement



Notifications



Please check our latest addition

C#, PYTHON and DJANGO


Advertisement