Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'using' keyword to choose from multiple virtual inherited functions

Tags:

People also ask

Can multiple inheritance have virtual classes?

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.

What is the use of virtual keyword in inheritance?

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.

Can we use virtual keyword in derived class?

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.

Why does virtual keyword used during new class derivation?

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")