#include <iostream>
struct B1
{
virtual void method()=0;
virtual ~B1(){}
};
struct B2
{
virtual void method()=0;
virtual ~B2(){}
};
struct D: B1, B2
{
virtual void method()
{
std::cout << "D::method\n";
};
};
int main(int argc,char *argv[])
{
D d;
B1 &b1=d;
B2 &b2=d;
b1.method();
b2.method();
return 0;
}
Note, B1 and B2 do not share common interface.
Is it this legal? If yes - in which standard? C++98/03/11 ?
Both, msvc and gcc have compiled it OK.
Previously I thought, that I have to use some common interface for such case (possible virtual inheritence).
Does such situation have some special name?
How it works in details, please? Maybe some ISO references?
Because virtual functions are called only for objects of class types, you cannot declare global or static functions as virtual . 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.
It is not mandatory for the derived class to override (or re-define the virtual function), in that case, the base class version of the function is used. A class may have virtual destructor but it cannot have a virtual constructor.
If you don't override a pure virtual function in a derived class, that derived class becomes abstract: class D2 : public Base { // no f1: fine.
You cannot override a non-virtual or static method. The overridden base method must be virtual , abstract , or override . An override declaration cannot change the accessibility of the virtual method. Both the override method and the virtual method must have the same access level modifier.
Your code is well-formed: void D::method()
overrides both void B1::method()
and void B2::method()
.
The specification states (C++11 §10.3/2):
If a virtual member function
vf
is declared in a classBase
and in a classDerived
, derived directly or indirectly fromBase
, a member functionvf
with the same name, parameter-type-list, cv-qualification, and ref-qualifier (or absence of same) asBase::vf
is declared, thenDerived::vf
is also virtual (whether or not it is so declared) and it overridesBase::vf
.
B1
declares a virtual member function void B1::method()
. Class D
is derived from B1
and it also declares a member function with the same name (method
), the same parameter list (no parameters), the same cv-qualification (no qualification) and the same ref-qualifier (no qualification).
Therefore, void D::method()
overrides void B1::method()
.
The same logic applies for void B2::method()
(just substitute B2
for B1
in the above explanation), so void D::method()
overrides both void B1::method()
and void B2::method()
.
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