Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why subclass method isn't called?

I have problem with subclassing and using methods.

I create an instance of class B and store it as a pointer to A. But when I use the pointer to call the overloaded method, the output is "A" not "B". Why?

This works in other languages, what am I doing wrong?

#include <iostream>
using namespace std;

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

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

int main() {
    A *a = new B();
    a->f();
    return 0;
}
like image 388
eSeverus Avatar asked Feb 18 '13 15:02

eSeverus


2 Answers

f() needs to be declared virtual in the base class A:

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

The other languages you already worked with may default to virtual methods, but C++ doesn't (don't pay for what you don't use: virtual methods incur an indirection when calling them which means they are slightly slower than normal method calls).

By adding virtual, binding will be postponed to runtime (called dynamic binding) and which f() function call will be decided on the type of the value.

Because you have not declared function f() as virtual, binding is static (at compilation time) and will use the type of variable (but not value) to determine which f() to call. So in your present code statment a->f(); calls the A class's f() because a is pointer to the A class.

like image 55
syam Avatar answered Oct 29 '22 03:10

syam


In order to achieve polymorphic behavior, the method of the base class must be virtual.

So in class A you need to change void f() to virtual void f().

like image 30
LihO Avatar answered Oct 29 '22 05:10

LihO