vendredi 31 août 2018

virtual base classes initiailization

I am working on a test and I have hard time to understand this one:

#include <iostream>

struct Car
{
 Car() : price(20000) {}
 Car(double b) : price(b*1.1) {}
 double price;
};
struct Toyota : public virtual Car 
{
 Toyota(double b) : Car(b) {}
};

struct Prius : public Toyota
{
 Prius(double b) : Toyota(b)  {}
};

int main(int argc, char** argv)
{
 Prius p(30000);

 std::cout << p.price << std::endl;

 return 0;
}

The returned value is 20 000, but actually I do not not understand the why:

All sub-objects representing virtual base classes are initialized by the constructor of the most derived class. If the constructor of the most derived class does not specify a mem-initializer for a virtual base class V, then V's default construtor is called to initialize the virtual base class subobject.

And I tried different way to create a constructor in the derived class but I got errors from the compiler.

Does anyone provide an explnantion and how to creatse such constructor? Thank you very much for your help

Aucun commentaire:

Enregistrer un commentaire