Search code examples
c++inheritancepolymermember-functions

Access child member methods from function taking parent class


A test function needs to take in any object of a class that is derived from Parent and access the Child implementation of Function(). To me, this would seem like something easy to do. I tried to do the following. it feels intuitively right, but it does not work. It still calls the Parent implementation of Function()

Class Parent
{
Public:
    Parent();
    ~Parent();

    virtual void Function() = 0;

};

Class Child : public Parent
{
Public:
    Child();
    ~Child();
    void Function(){
        // Do something
    };
};

void Test(Parent Object)
{
    Object.Function();
};

int main()
{
    Child Object;
    Test(Child);
    return 0;
}

How would one implement such a thing?

Am I missing something small? or is this solution far off what I am trying to achieve?

Thanks in advance.


Solution

  • To use virtual functions in C++ you must use a reference or a pointer. Try this

    void Test(Parent& Object) // reference to Parent
    {
        Object.Function();
    };
    

    You should research object slicing to understand what goes wrong with your version, and why you must use a reference or a pointer.