Reputation: 7253
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
Upvotes: 0
Views: 155
Reputation: 258548
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();
Upvotes: 2