Ruchi
Ruchi

Reputation: 693

copy constructor in derived class

I have a base class and there are few classes being derived from it. I have not written any copy constructor in the base class, it is using the default one.

So if I write this code:

base* b;
b = new base(*this)

it works fine, but if I write something like this:

base* b;
b = new derive(*this) 

it gives me an error for no matching function in the derived class.

Can't I pass base class' this pointer to its derived class copy constructor to get it initialized?

Upvotes: 1

Views: 2958

Answers (3)

Jesper
Jesper

Reputation: 206786

No, you can't. There could be other subclasses of base. If the copy constructor of class derive would accept a const base&, then you could pass it an instance of another subclass of base. The copy constructor of class derive wouldn't know what to do with such an object.

Upvotes: 0

steffen
steffen

Reputation: 8958

Overload the derived contructor with a version that takes the base class as parameter. That should work.

Upvotes: 0

Andrew
Andrew

Reputation: 24846

Derived copy constructor takes const Derived & as it's argument. You can't use const Base & as an argument.

You are trying to do:

Derived *d = new Derived();
Base *b = new Base(*d); //ok, since Derived is subclass of Base

Base *b = new Based();
Derived *d = new Derived(*b); //error, since Base in not subclass of Derived

In order to construct Derived from Base you need to provide such constructor yourself:

Derived(const Base &base) {...}

Upvotes: 3

Related Questions