Virtual inheritance constructor selection

  • A+
Category:Languages

Why does this print 20000? Code explicitly calls specific base constructors all the way up the inheritance train, yet ignores specified constructor and uses the default constructor instead.

#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; } 


Virtual base class must be constructed by the most-derived class; that's the only way that makes sense considering the possibility of a diamond-shaped hierarchy.

In your case, Prius constructs Car using its default constructor. If you want the other constructor, you'd have to call it explicitly, as in

Prius(double b) : Car(b), Toyota(b) {} 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: