0

Being a Java Programmer and a C++ noob, I'm having a tough time dealing with inheritance in C++. Right now, I have this:

class Parent {
public:
    Parent() {}
    virtual std::string overrideThis() { }
};

class Child : public Parent {
public:
    std::string attribute;
    Child(const std::string& attribute) : attribute(attribute) { }
    std::string overrideThis(){
    std::cout << "I'm in the child" << std::endl;
    return attribute.substr(1, attribute.size()-2);
    }
};

And this snippet somewhere else:

Child *child = new Child(value);
Child childObject = *(child);
std::cout << "I'm trying this: " << childObject.overrideThis() << endl;

The code above works as expected a the message is printed on screen. But if instead of that I try this:

Child *child = new Child(value);
Parent childObject = *(child);
std::cout << "I'm trying this: " << childObject.overrideThis() << endl;

I have a funny runtime error with lots of funny characters on my Screen. What's the proper way of using polymorphism with pointers? What I'm trying to do is invoke overrideThis() on a Child instance

1 Answer 1

2

The program has undefined behavior because the function that is being called -Parent::overrideThis doesn't return, although it should.

The function in the Parent class is called because Parent childObject = *(child); slices the object the you attempt to copy - the new object, childObject is of type Parent, not Child.

For polymorphism to work, you need to use either pointers or references:

Parent* childObject1 = child;
Parent& childObject2 = *child;
childObject1->overrideThis();
childObject2.overrideThis();
Sign up to request clarification or add additional context in comments.

4 Comments

And how can I invoke overrideThis() on a reference? (Sorry if is a naive question xD)
In which way I can invoke overrideThis()? Neither allow me to do childObject.overrideThis()
What about dynamic_cast?
@IgnacioVazquez-Abrams what about it?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.