How to call derived class method from base class pointer?

You need to make DoSomething() a virtual function in both classes to get the polymorphic behavior you’re after:

virtual void DoSomething(int i) { ...

You don’t need to implement virtual functions in every sub class, as shown in the following example:

#include <iostream>

class A {
    public:
        virtual void print_me(void) {
            std::cout << "I'm A" << std::endl;
        }

        virtual ~A() {}
};

class B : public A {
    public:
        virtual void print_me(void) {
            std::cout << "I'm B" << std::endl;
        }
};

class C : public A {
};

int main() {

    A a;
    B b;
    C c;

    A* p = &a;
    p->print_me();

    p = &b;
    p->print_me();

    p = &c;
    p->print_me();

    return 0;
}

Output:

I’m A
I’m B
I’m A

Leave a Comment