0

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.

asmmo
  • 6,922
  • 1
  • 11
  • 25
  • Please edit your question to show the real code. – G.M. Mar 22 '20 at 10:54
  • `Parent.Function();` should be `object.Function();` and the same with the Child object. note that you are passing a copy of the Child object and it will be sliced. the polymorphic behavior can be demonstrated by pointers not by ordinary objects. – asmmo Mar 22 '20 at 11:05
  • @G.M. what do you mean with the real code? – V. Voorspel Mar 22 '20 at 11:09
  • Sorry but have you tried to compile the code as shown. It's important that the code you provide is, as I said, the *real* code. – G.M. Mar 22 '20 at 11:16

1 Answers1

2

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.

john
  • 85,011
  • 4
  • 57
  • 81