As a student , I was testing out various ways of invoking the copy constructor . I came across 3 of them :
Test t2 = t1 // 1 ;
Test t3(t1) // 2 ;
Test t4 ; // 3 ;
t4 = t1 ;
The explicitly defined copy constructor adds 10 to each of the data members of t1 . The first 2 work fine and call the explicit one . However the 3rd approach calls the implicit copy constructor i.e. there is no addition of 10 taking place .
My code :
#include <iostream>
using namespace std ;
class Test
{
int m,n ;
public:
Test() ;
Test(int,int) ;
~Test() ;
Test(Test&) ;
void showData() ;
};
inline Test::Test(Test& t)
{
cout<<"called"<<endl ;
m = t.m + 10 ;
n = t.n + 10 ;
}
inline Test::Test(){}
inline Test::Test(int m,int n)
{
Test::m = m ;
Test::n = n ;
}
inline Test::~Test(){}
inline void Test::showData()
{
cout<<m<<" "<<n<<endl ;
}
int main()
{
Test t1(3,4) ;
t1.showData() ;
Test t2(t1) ;
t2.showData() ;
Test t3 = t1 ;
t3.showData() ;
Test t4 ; //calls the implicit one
t4 = t1 ;
t4.showData() ;
return 0 ;
}
Output :
3 4
called
13 14
called
13 14
3 4
I tried overloading the assignment(=) operator to manually solve the problem with the 3rd approach which did work , but I want to know why the 3rd approach calls the implicit copy constructor even though an definition has been provided explicitly .
this, not just"called". That way you know exactly what object(s) are being created, copied, and destroyed (your destructor doesn't output any information).coutstatements in their code, but this works too. From OP’s language and comprehensive test it sounds to me like he has a pretty good grasp on what a copy constructor should actually do.