Advertisement



< Prev
Next >



C++ Constructor





In C++, a constructor is special member function of class which is used to create and initialize its objects. 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.

A.cpp
#include<iostream>

using namespace std;

class A
{
private:
int a,b;

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

A( A & ob)
{
	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()
{
A ob1(2,4);	//private constructor of A class is called outside its class, hence compile error.
cout<< "The value of data member a and b of the first object" <<"\n";
ob1.show_ab();

//Calling 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

PYTHON


Advertisement