0

I have this snippet:

#include <iostream>
#include <vector>

class A {
public:
    void m() {
        std::cout << "hi";
    }
};

class B : public A {
public:
    void m() {
        std::cout << "hello";
    }
};

int main() {
    std::vector<A*> v;
    v.push_back(new A);
    v.push_back(new B);
    v.push_back(new A);
    for (A *obj : v)
        obj->m();
}

The problem is that this program prints hihihi instead of hihellohi, and it means that it always calls the m() method of the static type (i.e. A) rather than the dynamic one (B). How can we always call the m() method of the dynamic type?

Thank you for your help.

JacopoStanchi
  • 1,962
  • 5
  • 33
  • 61

1 Answers1

1

Base class function should be virtual in order to have polymorphic behaviour:

class A {
public:
    virtual void m() {  // <-- You missed this virtual
        std::cout << "hi";
    }
};

and for derived class, it should be override:

class B : public A {
public:
    void m() override {
        std::cout << "hello";
    }
};
artm
  • 17,291
  • 6
  • 38
  • 54