Max Popov
Max Popov

Reputation: 397

Constructor from reference to parent class in polymorphism

Is it possible to make constructor in derived class which receives reference of the parent class pointing to another child class?

Child ch;
Parent &pr = ch;
Child ch1 = pr;

I guess it might be something like this:

Child(const Parent &pr){
*this = dynamic_cast<Child>(pr);
//Invalid target type 'Parent' for dynamic_cast; 
//target type must be a reference or pointer type to a defined class
}

Upvotes: 2

Views: 87

Answers (1)

Ted Lyngmo
Ted Lyngmo

Reputation: 117328

It looks like you want to delegate to the Child's copy constructor:

Child(const Parent& pr) :
    Child(dynamic_cast<const Child&>(pr))
//                     ^^^^^^^^^^^^
//              note:     const&
{}

If the Parent/Child relationship isn't the expected, you'll get a bad_cast exception.

Demo

Upvotes: 1

Related Questions