I have a question about virtual functions in C++, for example, A is a base class, and class B inherits A, and class C inherits B, can we define a virtual function in B, and redefine it in C? What I mean is, should this virtual function be defined in class A, because A is the base class (i.e the root of B and C) for all the B and C?
Not it does not have to be ... B is a specialized object from A and it is high likely B has more features than A has. And if C is derived, it is very normal to have a function overridden from B which is not defined in A.
Example
virtual can be used anywhere in a class hierarchy, but that virtual function can only be overridden in the sub-classes (i.e. it does not apply to the super classes).
struct A {
void funcA();
};
struct B : A {
virtual funcB();
};
struct C : B {
virtual funcB();
};
//....
B* b = new C();
b->funcB(); // calls C's implementation
A* a = new C();
a->funcB(); // fails to compile
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