I understand that the copy constructor is invoked when a new object based on an existing object is created. However I have been trying to do the same, and I find that the copy constructor is not being invoked. Following is my piece of code:
/*
* class definition
*/
class A
{
public:
A(int mn, int mx); //default constructor
A(A const& obj); //copy constructor
~A();
private:
int* ptr;
int max;
int min;
}
class B
{
public:
B();
void print();
private:
A m_aObject;
}
/*
* B.cpp
*/
void B::print()
{
A local_obj1(2,3);
local_obj1.ptr = Global_array; //some global array.
m_aObject = local_obj1; // should invoke the copy constructor
}
/*
* A.cpp
*/
A::A(A const& obj)
{
cout << "copy constr. invoked"<<endl;
ptr = new int[10];
for(int i= 0; i< 10; i++)
ptr[i] = obj.ptr[i];
}
A::A(int mx, int mn)
{
min = mn;
max = mx;
}
As per the link [https://www.tutorialspoint.com/cplusplus/cpp_copy_constructor.htm], the line m_aObject = local_obj1;
must invoke the copy constructor.
However I see that after the execution of the above statemment, the copy constructor is never invoked. The print inside the copy constr. is never displayed on the console.
Does the line m_aObject = local_obj1;
really invoke the copy constr. ?
If I try invoking the copy constr. by m_aObject(local_obj1);
,
it gives a compilation error error: no match for call to '(A) (A&)'
Is there any other way of invoking the copy constructor for the above case.