C++ Copy Construction of Static Object

#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?

Upvotes: 0

Views: 1119

Answers (4)

B Jacob
B Jacob

Reputation: 389

Be aware that, Compiler will create a default copy constructor, if you don't define one. This does a shallow copy meaning copies each member of the class individually using the standard assignment operator ('=').

 x=obj.x;

Since this is exactly what you would be doing anyway, there is really no reason to override.

This works well if you have a simple class with no dynamically allocated memory (or pointers). However if you want to copy a pointer (pointing to a chunk of data) shallow copy doesn't work. This is because the assignment operator just copies the address of the pointer and not allocate any memory or copy the contents being pointed to.

Upvotes: 0

jpo38
jpo38

Reputation: 21544

The behaviour is correct, copy constrcutors are called as they should be...but:

If you want two.xto be 30, you need to copy the x value within your copy constructor...which is not the case in your code. You just print A's copy constructor called but your copy constructor has no effect.

Just change it to

A(const A& obj)
{ 
    cout<<"A's copy constructor called " <<endl; 
    x = obj.x; // added!
}

Then, program displays:

A's constructor called 
A's constructor called 
A's copy constructor called 
30
30
30

Upvotes: 1

ravi
ravi

Reputation: 10733

two is initialized using copy constructor you defined. And in that definition you have not assigned any value to x. That's why it's printing garbage.

Upvotes: 0

kraskevich
kraskevich

Reputation: 18566

You have defined your own copy constructor that does not copy the value of x. So it is left uninitialized.

Upvotes: 4

Related Questions