Inheritance question

I have a parent class with 2 child class. I want to use dynamic casting to change my parent class from base to derived so that I can access the data and methods in the child classes. Also, I am using array for the code. Is there any examples of how can I do the dynamic casting for reference? And also is there any sample coding that can access the mutator and accessor to get and set the inputs? Thank you
. I want to use dynamic casting to change my parent class from base to derived so that I can access the data and methods in the child classes


This suggests a mistake has been made in the design. C++ provides virtual functions to do this. As a strong rule of thumb, you shouldn't need to dynamically cast a parent to a child.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>

class parent
{
    public:
    virtual void virtualFunction() {std::cout << "parent::virtualFunction() called \n";}
    void nonVirtualFunction() {std::cout << "parent::nonVirtualFunction() called \n";}
};


class child : public parent
{
    public:
    void virtualFunction() {std::cout << "child::virtualFunction() called \n";}
    void nonVirtualFunction() {std::cout << "child::nonVirtualFunction() called \n";}
};

int main()
{
    child aChildObject;
    parent& parentRef = aChildObject;
    parentRef.virtualFunction(); // VIRTUAL FUNCTION CALLED SO WE GET THE MOST DERIVED IMPLEMENTATION - THE CHILD IMPLEMENTATION
    parentRef.nonVirtualFunction(); // NOT VIRTUAL FUNCTION, SO PARENT FUNCTION CALLED BECAUSE THIS IS A REF_TO_PARENT
    
    aChildObject.nonVirtualFunction(); // CHILD FUNCTION CALLED BECAUSE OBJECT IS  A CHILD OBJECT
}

Last edited on
Topic archived. No new replies allowed.