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?
No, you cannot override a non-virtual method. The closest thing you can do is hide the method by creating a new method with the same name but this is not advisable as it breaks good design principles.
It is not mandatory for the derived class to override (or re-define the virtual function), in that case, the base class version of the function is used.
When you override a function you don't technically need to write either virtual or override . The original base class declaration needs the keyword virtual to mark it as virtual. In the derived class the function is virtual by way of having the ¹same type as the base class function.
The virtual keyword can be used when declaring overriding functions in a derived class, but it is unnecessary; overrides of virtual functions are always virtual. Virtual functions in a base class must be defined unless they are declared using the pure-specifier.
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.
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With