jeudi 23 janvier 2020

C++ inheritance - why is parent method called?

I am implementing a class hierarchy and see calls to parent methods that I do not understand why. Using C++11 constructs and this is my first 11 project where I use some features, hence I believe this might be a benign problem.

class A{
   void update(){
       std::err << "Calling A update " << std::endl;
   } 
}

class B: public A{
   void update(){
       std::cout << "In B update! " << std::endl;
   } 
}

class C: public A{
   void update(){
       std::cout << "In C update! " << std::endl;
   } 
}

now somewhere else I have a vector containing either Bs or Cs

std::vector<A> container;
container.push_back(B());
container.push_back(C());

for(auto item: container){
    item.update();
}

prints

Calling A update
Calling A update

Why?

Aucun commentaire:

Enregistrer un commentaire