Initializing virtual inheritance hierarchy
-
30-06-2021 - |
Pergunta
Consider the following virtual inheritance hierarchy
#include <string>
#include <iostream>
struct base
{
base() = default;
base( std::string const& s ) : s_(s) {}
std::string print() { return s_; }
private:
std::string s_;
};
struct derived : virtual base
{
derived( std::string const& s ) : base( "cool formatting: " + s ) {}
};
struct more_derived : virtual derived
{
more_derived( std::string const& s ) : derived( "even cooler formatting: " + s ) {}
};
int main()
{
std::cout << more_derived( "foo" ).print() << std::endl;
}
Desired output:
cool formatting: even cooler formatting: foo
The code doesn't print anything because more_derived
is not explicitly calling the base
constructor that takes a string, and so the default base
constructor is called. Moreover, due to virtual
inheritance derived
's initialization of base
is ignored.
How can I get the desired output while maintaining virtual inheritance and not having to call each base class constructor explicitly?
EDIT:
I realize what I'm asking for is not possible using constructor calls down the inheritance hierarchy because of virtual inheritance. I was hoping someone could provide an alternate method that would produce the desired result upon construction of most_derived
.
Solução
You are asking for two contradictory goals. On one side you want to maintain virtual inheritance (do you really need it?) and on the other side you want the constructor not to be called from the most derived type directly.
You cannot get both, so pick one. You can of course pass the desired string from the most derived type, but I am guessing that the point is not the actual value, but the fact that the value is constructed from the bottom up...