16

I am trying to understand a point here in C++. If class A has a non-virtual method, and class B, which extends A, overrides that method, can i create an instance of B and somehow use the method defined in B? Is there a point to override a non-virtual method?

1

4 Answers 4

38

Is there a point to override a non-virtual method?

You are not actually overriding, but this is the behavior, i.e

B* b = new B();
A* a = new B();
b->method(); //Calls B's method
a->method(); // Calls A's method

So, the pointer/reference type determines the method called.

can i create an instance of B and somehow use the method defined in B?

Yes. The pointer/reference type has to be of type B. (see previous example).

If you don't declare method to be virtual, you cannot override it, but you can hide it.

3
  • 1
    One "gotcha" is the situation when A in turn is derived from some base class (or implements an interface) which declares virtual method(), in which case a->method() will in fact call B.method()...
    – Magnus
    Mar 19, 2016 at 13:06
  • @Chip You missed to emphasize the difference. This answer is complete only with BadCashs comment. May 31, 2016 at 12:59
  • 1
    @ManuelSchneid3r While you are right, in BadCash's case A's method is virtual. The question was about non-virtual methods. In C++, "once virtual, always virtual".
    – Chip
    Jun 1, 2016 at 6:43
13

If B inherits from A, and redefines a method defined in A, then new instances of B will call B's version. However, if the method is not virtual, then there is no polymorphic behavior, so if an instance of B is referenced as an A, then the method will be A's. For example:

struct A {
    void foo () { std::cout << "A::foo" << std::endl; }
};

struct B : public A {
    void foo () { std::cout << "B::foo" << std::endl; }
};

B b;
b.foo();
A *a = &b;
a->foo();

The output of the code above would be:

B::foo
A::foo

However, if the foo method had been virtual, then B::foo would have been printed twice.

1
  • Well written! :)
    – niknak
    Jun 4, 2017 at 1:09
4

If a function is not virtual then the type of the variable determines which implementation is dispatched too:

#include <iostream>

using namespace std;

struct A {
    void f() { cout << "A" << endl; }
};

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

int main(int args, char** argv) {

    B b;
    A& a = b;

    b.f();
    a.f();

    return 0;
}
0
  • No, there is no mechanism to override a non-virtual method in class A.
  • Yes, you can use a non-virtual method from class A overloaded in B by using scope resolution operator A::methodName

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.