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!
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.
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) { }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With