anupamb
anupamb

Reputation: 482

Why constructor does not work in some cases?

I have a class definition. And I am confused about some constructor behaviour. Following is the code.

#include <iostream>
#include <cstdlib>

using namespace std;

class A
{
  int i;
public:
  void seti(int v) {cout << "Setting i\n"; i=v;}
  void print() {cout << "i = " << i << endl;}
  A(){};
  A(int v) {cout << "Setting i in par-ctor to " << v << "\n"; i=v;}
  A(A& o) {cout << "In copy ctor, changing i to " << o.i << "\n";i=o.i;}
  A& operator=(A o) {cout << "In assignment op\n"; this->i = o.i; return(*this);}
};

int main()
{
  A o1;
  A o2(2);
  A o3 = A(4);
  A o4 = 35;

  return(0);
}

I want to know why this code does not compile unless

a) The defined copy constructor is commented, or

b) The defined copy constructor has a 'const' qualifier as in A& A(const A& o) or

c) Object initializations for both o3 and o4 are removed.

Regarding (c) in which the invocation of constructor A(int) is expected,

How does the actual copy constructor definition (the one without const) conflict with the parametrized (with int) constructor ?

Upvotes: 1

Views: 88

Answers (1)

Joseph Mansfield
Joseph Mansfield

Reputation: 110648

First look here:

A o3 = A(4);

The A(4) creates a temporary object. This expression is an rvalue. An rvalue cannot bind to a non-const lvalue reference like A&, so the copy constructor cannot be chosen. A better copy constructor declaration has a const A&, so that it can be constructed from rvalues too. That's why your (b) fix works.

The same problem manifests here:

A o4 = 35;

In copy-initialisation (with an =), a temporary of the object is constructed and then copied into the object you're declaring. So this is equivalent to:

A o4 = A(35);

And therefore exhibits the same problem as above.

Upvotes: 6

Related Questions