Atul
Atul

Reputation: 1151

Copy constructor problem

I tried to use copy constructor using statement:

X y = X();

But copy constructor is not being called. I am using g++ 4.1.0. I set both X(const X&) and X(x&) constructor in the class.

Is this supposed to work or I am doing some very basic problem in the code?

My code for the class is

class A
{
 public:
  int i;

  A(int ii)
  {
   i = ii;
  }

  A(const A&)
  {
   i = 5;
  }

  A(A&)
  {
   i = -1;
  }

  A()
  {
   i = 5000;
  }
};

When I use it using A a = A(); or A a = A(100);, it does not work but when i use it A a(b); or A a = b; it works fine.

What is the point I am missing? I saw that according to wikipedia , it should work but it's not working in my case :(.

Thanks in advance for all your answers and comments.

Upvotes: 2

Views: 1730

Answers (4)

LostMohican
LostMohican

Reputation: 3144

Copy constructors are called when you initialize an object with an another object:). In your first example it is totally natural that the copy ctors are not called, only constructors with the suitable parameter lists will be called.

Upvotes: -1

Dunya Degirmenci
Dunya Degirmenci

Reputation: 395

The copy constructor is called by the statements X x(y); or X x = y;.

When you call X x = X();, the default constructor is called.

When you call X x = X(100);, a constructor with one parameter is called. These are not copy constructors.

Upvotes: 0

James McNellis
James McNellis

Reputation: 354999

The compiler is permitted to elide the call to the copy constructor in certain situations. Initializing an object from a temporary is one of them. In this case, the temporary is simply constructed in-place instead of constructing a temporary and then copying it into the named object.

You can call the copy constructor by constructing a named object then making a copy of that:

X x;
X y = x;

Upvotes: 13

Roman Starkov
Roman Starkov

Reputation: 61382

X y = X();

calls the default constructor. The copy constructor is the one that takes a reference to an instance you want copied.

The point of a copy constructor is to take another object of the same type, and make a copy of it. Everything else is not a copy constructor.

Upvotes: 1

Related Questions