Search code examples
c++inheritancemethodsvirtual

C++ virtual method confusion


I have a basic C++ question about inheritance and virtual methods.

Please regard this code:

#include <iostream>
#include <vector>
using namespace std;

class A {
public:
  virtual void f() {cout << "A\n";};
};

class B : public A {
public:
  void f() {cout << "B\n";};
};

int main() {
  A a;
  B b;
  vector<A> v;
  v.push_back(a);
  v.push_back(b);

  for (int i = 0; i < v.size(); ++i)
    v.at(i).f();
}

If I execute this code, it prints out

A
A

I do not understand why it does not print

A
B

because the "f" method is declared as virtual. I would like to know why the program behaves in this way.

Thanks in advance


Solution

  • Your vector contains A objects:

    vector<A> v;
    

    when you push_back a B object into it, the vector copies the A part of it into a new A object. It is the equivalent of doing this:

    A a;
    B b;
    a = b;
    a.f();
    

    This is called object slicing.