#include <iostream>
using namespace std;
class A
{
public:
int x;
A(){x= 30; cout << "A's constructor called " << endl;}
A(const A& obj) { cout<<"A's copy constructor called " <<endl; }
};
class B
{
public:
static A sample;
B() { cout << "B's constructor called " << endl; }
static A getSample() { return sample; }
};
A B::sample;
int main()
{
A one;
A two = B::getSample();
cout<<B::sample.x<<endl;
cout<<one.x<<endl;
cout<<two.x<<endl;
return 0;
}
The code above outputs:
A's constructor called
A's constructor called
A's copy constructor called
30
30
-1032819680
Why does not copy constructor copy value of x to B::getSample(). In another words, while B::getSample()=30, why two.x is -1032xxxxxx?
The behaviour is correct, copy constrcutors are called as they should be...but:
If you want
two.xto be30, you need to copy thexvalue within your copy constructor...which is not the case in your code. You just printA's copy constructor calledbut your copy constructor has no effect.Just change it to
Then, program displays: