Virtual base classes are used in virtual inheritance in a way of preventing multiple “instances” of a given class appearing in an inheritance hierarchy when using multiple inheritances.
Virtual keyword is used to avoid ambiguity in inheritance. That is to resolve the ambiguity when there is/are member function with same prototype in multiple base classes.
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.
Adding the "virtual" keyword is good practice as it improves readability , but it is not necessary. Functions declared virtual in the base class, and having the same signature in the derived classes are considered "virtual" by default.
I have a class ('TestC'), which is derived from two other classes ('TestA' and 'TestB'), both of which have a virtual function with the same signature.
To make the function accessible through 'TestC', I have to tell it which version to use. This works if I explicitly overwrite the function in 'TestC' and call the version I want:
#include <iostream>
class TestA
{
public:
virtual void test() {std::cout<<"a";}
};
class TestB
{
public:
virtual void test() {std::cout<<"b";}
};
class TestC
: public TestA,public TestB
{
public:
void test() {TestB::test();}
};
int main(int argc,char *argv[])
{
TestC c;
TestA *a = static_cast<TestA*>(&c);
a->test();
c.test();
for(;;);
return EXIT_SUCCESS;
}
Output: "bb"
That's the expected result. However, I noticed that if I use the 'using' keyword, instead of overwriting the function explicitly, I get some unexpected behavior:
class TestC
: public TestA,public TestB
{
public:
using TestB::test;
};
(Everything else is the same)
Output: "ab"
Can someone explain this to me? It looks like 'test' is suddenly not virtual anymore? Is there any way to do this, without explicitly overwriting the function? (Something like "using override")
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