Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ inherited copy constructor call ?

I have class B derived from class A. I call copy constructor that I implemented myself for an object of class B. I also implemented myself a constructor for class A.

Is this copy constructor automatically called when I call copy constructor for class B ? Or how to do this ? Is this the good way:

A::A(A* a)
{
    B(a);
    // copy stuff
}

thanks!

like image 482
kiriloff Avatar asked Sep 28 '12 12:09

kiriloff


2 Answers

You can do this with a constructor initialization list, which would look like this:

B::B(const B& b) : A(b)
{
    // copy stuff
}

I modified the syntax quite a bit because your code was not showing a copy constructor and it did not agree with your description.

Do not forget that if you implement the copy constructor yourself you should follow the rule of three.

like image 56
Jon Avatar answered Oct 13 '22 12:10

Jon


A copy constructor has the signature:

A(const A& other)  //preferred 

or

A(A& other)

Yours is a conversion constructor. That aside, you need to explicitly call the copy constructor of a base class, otherwise the default one will be called:

B(const B& other) { }

is equivalent to

B(const B& other) : A() { }

i.e. your copy constructor from class A won't be automatically called. You need:

B(const B& other) : A(other) { }
like image 33
Luchian Grigore Avatar answered Oct 13 '22 12:10

Luchian Grigore