Home > database >  Constructor from reference to parent class in polymorphism
Constructor from reference to parent class in polymorphism

Time:11-05

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
}

CodePudding user response:

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

  • Related