0

I know many examples are on stackoverflow regarding copy constructors. However, I have not seen one with my specific problem.

Suppose I have a base class Base that is defined like this:

class Base
{
public:
    Base(const Base &other);
    ...
}

and that I have a derived class Derived that is defined like this:

class Derived
{
public:
    Derived(const Base &other); //construct from base class
    Derived(const Derived &other); //construct from derived class (copy constructor)
}

Can the copy constructor be defined like this?

Derived::Derived(const Derived &other) : Base(other) {...}

Or is this not good style in C++? If not, how can I get the same result using a better method? My compiler (MSVC) doesn't seem to complain about it.

owacoder
  • 4,815
  • 20
  • 47
  • 1
    This is exactly the way you should initialize the base class in a copy constructor... – Rostislav Oct 10 '15 at 16:36
  • @Rostislav - So will the `other` in the copy constructor be converted to a `Base` before being passed to the base class' copy constructor? – owacoder Oct 10 '15 at 16:37
  • It will do the usual overload resolution. And normally this is unambiguously select the correct constructor. Of course you could create an artificial example where it's not the case, but it's just poor design then. – Rostislav Oct 10 '15 at 16:39
  • Yes exactly, `Derived` is a kind of `Base`, so il will be converted without any action from your side. Your code is good. – S.Clem Oct 10 '15 at 16:39

1 Answers1

1

to implement

Derived::Derived(const Derived &other) : Base(other) {...}

you have to create base constructor:

Base(const Base &other);
vishal
  • 2,258
  • 1
  • 18
  • 27