Tim
Tim

Reputation: 99428

Is this a valid Copy Ctor ?

I wonder if there is something wrong with the copy constructor function below?

class A
{
   private:
      int m;
   public:
      A(A a){m=a.m}
}

Upvotes: 3

Views: 419

Answers (3)

alexkr
alexkr

Reputation: 4670

There 3 problems.

First, you have forgot ";" at the end of the m=a.m so your code would not compile.

Second, passing by reference is preferred in most cases where you pass something with size greater than size of a register on your platform.

Third, since you are not going to change the source object, it is better to have it with const. So, finally this is what we have:

A(const A & a) : m(a.m) {}

Upvotes: 7

anon
anon

Reputation:

Two things:

  • Copy constructors must take references as parameters, otherwise they are infinitely recursive (in fact the language won't allow you to declare such constructors)

  • It doesn't do anything the default copy ctor doesn't do, but does it badly - you should use initialisation lists in a copy ctor wherever possible. And if the default copy ctor does what you want, don't be tempted to write a version yourself - you will probably only get it wrong, and you will need to maintain it.

Upvotes: 17

AProgrammer
AProgrammer

Reputation: 52294

The problem is that the copy constructor is called for parameter passed by value. So you have to pass the parameter of the copy constructor by reference (usually const reference) if you don't want a non terminating recursion. A minor issue is that you aren't using the initialization list, which is preferable to initialize the member. Fixing both issues:

A(A const& a)
  : m(a.m)
{}  

Upvotes: 5

Related Questions