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?
Is there a point to override a non-virtual method?
You are not actually overriding, but this is the behavior, ie
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.