C ++: field exchange between a class and superclasses

I got a little confused in the fields of class and superclass. I expected everything to be okay:

class SuperC { public: SuperC(); protected: double value; }; class C : public SuperC { public : C(double value); }; SuperC::SuperC(){} C::C(double value):SuperC(),value(value){} 

but the compiler tells me that C does not have a "value" field. C does not inherit from what is defined in SuperC?

many thanks

+4
source share
2 answers

It does, but you can only initialize the current members of the class using the syntax of the constructor initialization list.

You will need to create an overloaded constructor in SuperC that initializes the value and calls this.

 class SuperC { public: SuperC(); SuperC(double v) : value(v) {} protected: double value; }; class C : public SuperC { public : C(double value); }; SuperC::SuperC(){} C::C(double value):SuperC(value){} 
+8
source

You cannot initialize the members of the base class in the initialization list of the constructor of the derived class.

fix1: Maximum You can initialize the constructor of the base class (BC) in the derived class by passing the parametric code to BC.

fix2: assign base class members in constructor body of derived class instead of constructor initialization list

 C::C(double value1):SuperC() { value = value1; } 
+1
source

All Articles