I would like to understand WHY C++ standard mandates that virtual base non-default constructors cannot be invoked by an intermediate NOT most-derived class, as in this code, when compiled with '-D_WITH_BUG_' :
/* A virtual base's non-default constructor is NOT called UNLESS
* the MOST DERIVED class explicitly invokes it
*/
#include <type_traits>
#include <string>
#include <iostream>
class A
{
public:
int _a;
A(): _a(1)
{
std::cerr << "A() - me: " << ((void*)this) << std::endl;
}
A(int a): _a(a)
{
std::cerr << "A(a) - me:" << ((void*)this) << std::endl;
}
virtual ~A()
{
std::cerr << "~A" << ((void*)this) << std::endl;
}
};
class B: public virtual A
{
public:
int _b;
B(): A(), _b(2)
{
std::cerr << "B() - me: " << ((void*)this) << std::endl;
}
B(int b) : A(), _b(b)
{
std::cerr << "B(b) - me: " << ((void*)this) << std::endl;
}
B(int a, int b): A(a), _b(b)
{
std::cerr << "B(a,b) - me: " << ((void*)this) << std::endl;
}
virtual ~B()
{
std::cerr << "~B" << ((void*)this) << std::endl;
}
};
class C: public virtual B
{
public:
int _c;
C(): B(), _c(3)
{
std::cerr << "C()" << std::endl;
}
C(int a, int b, int c)
:
#ifdef _WITH_BUG_
B(a,b)
#else
A(a), B(b)
#endif
, _c(c)
{
std::cerr << "C(a,b) - me: " << ((void*)this) << std::endl;
}
virtual ~C()
{
std::cerr << "~C" << ((void*)this) << std::endl;
}
};
extern "C"
int main(int argc, const char *const* argv, const char *const* envp)
{
C c(4,5,6);
std::cerr << " a: " << c._a << " b: " << c._b << " c: " << c._c
<< std::endl;
return 0;
}
So, when compiled WITHOUT -D_WITH_BUG_, the code prints:
$ g++ -I. -std=gnu++17 -mtune=native -g3 -fPIC -pipe -Wall -Wextra \
-Wno-unused -fno-pretty-templates -Wno-register \
tCXX_VB.C -o tCXX_VB
$ ./tCXX_VB
A(a) - me:0x7ffc410b8c10
B(b) - me: 0x7ffc410b8c00
C(a,b) - me: 0x7ffc410b8bf0
a: 4 b: 5 c: 6
~C0x7ffc410b8bf0
~B0x7ffc410b8c00
~A0x7ffc410b8c10
But when compiled with -D_WITH_BUG_ :
$ g++ -I. -std=gnu++17 -mtune=native -g3 -fPIC -pipe -Wall -Wextra \
-Wno-unused -fno-pretty-templates -Wno-register \
-D_WITH_BUG_ tCXX_VB.C -o tCXX_VB
$ ./tCXX_VB
A() - me: 0x7ffd7153cb60
B(a,b) - me: 0x7ffd7153cb50
C(a,b) - me: 0x7ffd7153cb40
a: 1 b: 5 c: 6
~C0x7ffd7153cb40
~B0x7ffd7153cb50
~A0x7ffd7153cb60
Why must B(int a, int b)'s invocation of A(a) be ignored here ? I understand the C++ standard mandates it, but why ? What is the rational ?
If I instantiate just a B object : B b(4,5) ; this DOES get a correct b._a value of 4; but if B is a subclass of C: C c(4,5,6) C::a ends up being 1, IFF c does not DIRECTLY INVOKE A(a) . So the value of a B(a,b) is different if it is a subclass object than if it is a most-derived object . This to me is very confusing and wrong. Is there any hope of getting enough people to agree to change the C++ standard on this ?
_WITH_BUG_
) and names that contain two consecutive underscores are reserved for use by the implementation. Don't use them in your code.