In the example below I have my parent class and two child classes. Objects of either child are stored in a vector of parent. Looping over the vector I only see method invocations from the parent class. Please help me get the method definition and vtables right and how to avoid the slicing effect. Help, I have been doing python for too long where something like this would work.
#include <iostream>
#include <vector>
using namespace std;
int main()
{
class A{
public:
virtual string print(){return string("A");};
};
class B: public A{
virtual string print() final {return string("B");};
};
class C: public A{
virtual string print() final {return string("C");};
};
vector<A> v;
v.push_back(B());
v.push_back(C());
for(auto x : v){
cout << x.print() << endl;
}
}
=>
$g++ -std=c++11 -o main *.cpp
$main
A
A
Aucun commentaire:
Enregistrer un commentaire