Consider a Base class and a derived class that inherits from it called Child.
Assume the Base class has a member function declared virtual, and that Child overrides that function.
I would like to declare a variable as a Base class object, initialize it using the Child derived class constructor, and then use the Child class version of the member function.
In other words, the following C++ program:
#include <iostream>
class Base {
public:
virtual int give_number(int x) { return x; }
};
class Child : public Base {
public:
int give_number(int x) { return x+1; }
};
int main() {
Base base;
Child child;
Base child2;
child2 = Child();
std::cout << "Base says " << base.give_number(1) << "\n";
std::cout << "Child says " << child.give_number(1) << "\n";
std::cout << "Child2 says " << child2.give_number(1) << "\n";
}
results in the following output:
Base says 1
Child says 2
Child2 says 1
But I would instead prefer the following output:
Base says 1
Child says 2
Child2 says 2
Is there a way to accomplish this?
In the statement:
You are slicing the
Childobject, which is why theChild::give_number()method is not being called.child2is aBaseinstance, never aChildinstance. During the assignment, only theBaseportion of the newChildobject is copied intochild2.You must use a pointer or reference when calling a virtual method polymorphically, eg:
Or:
Or: