Is the "virtual" keyword optional in base classes in C++?
I'm trying to understand the function of the "virtual" keyword in C++ - consider this example:
#ifdef USE_VIRTUAL
struct a {
virtual void say_hi() { std::cout << "hello from a" << std::endl; }
};
#el开发者_开发技巧se
struct a {
void say_hi() { std::cout << "hello from a" << std::endl; }
};
#endif
struct b : public a {
void say_hi() { std::cout << "hello from b" << std::endl; }
};
int main( int argc, char** argc )
{
a a_obj;
b b_obj;
a_obj.say_hi();
b_obj.say_hi();
}
This program outputs:
hello from a
hello from b
regardless of whether or not a::say_hi is declared as virtual or not. Since the function gets correctly overridden even when say_hi is not declared virtual, then what is the function of declaring it as virtual?
You aren't using polymorphism. Polymorphic behaviour only affects pointers and references to base classes, like so:
class A; class B1 : A; class B2 : A;
B1 x;
B2 y;
A z;
A & a1 = x; // static type A&, dynamic type B1&
A & a2 = y; // static type A&, dynamic type B2&
A & a3 = z; // static and dynamic type A&
Now accessing member functions of a1
, a2
, a3
is subject to polymorphism and virtual dispatch.
However, you must declare the first function at the top of the inheritance hierarchy virtual, i.e. in A
! In your example, without virtual
, there's no polymorphism and you always call the member function of the corresponding static type of the object. To test this, add another few lines:
a & bref = b_obj;
bref.say_hi(); // call b::say_hi() if virtual, a::say_hi if not
bref.a::say_hi(); // always call a::say_hi()
精彩评论