Skip to main content

Posts

Showing posts with the label copy constructor

Copy Constructor

To understand the concept of copy constructor let us write a small program with a simple class A with two constructors. #include<iostream> using namespace std; class A { int num; public: A(); //default A( int m); //parameterized int getnum (); }; A :: A() : num( 0 ) { cout << "Default constructor" << endl; } A :: A( int m) : num(m) { cout << "Parameterized constructor" << endl; } int A :: getnum() { return num; } int main() { A obj1; A obj2 ( 10 ); A obj3 = obj1; cout << "That's all" << endl; } What is the output of this program? usha@dell:~/cppPrograms$ g++ copycons.cpp usha@dell:~/cppPrograms$ ./a.out Default constructor Parameterized constructor That's all Now the question is why do we have a call to only 2 constructors when we have created 3 objects in the main()? obj1 calls default constructor as it had no arguments. obj2 calls parame...