Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ : sharing fields between class and superclasses

I am a little confused about class and superclass sharing fields. I was expecting this to be ok:

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 C has no field "value". C does not inherit from the one defined in SuperC ?

many thx

like image 277
Vince Avatar asked Apr 12 '13 10:04

Vince


2 Answers

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

You'll have to create an overloaded constructor in SuperC that initializes value and call that.

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){}
like image 137
Luchian Grigore Avatar answered Nov 28 '22 10:11

Luchian Grigore


You can't initialize base class members in constructor initialization list of derived class.

fix1: At maximum You can initialize base class(BC) constructor in derived class by passing paramerter to BC.

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

C::C(double value1):SuperC()
 {
      value = value1;
 }
like image 34
shivakumar Avatar answered Nov 28 '22 10:11

shivakumar