0

If I try to do this:

class Particle {
    protected:
    double redshift_;
};

class Nucleus: public Particle {
    Nucleus(double z): redshift_(z) {}
};

I get a compiler error saying class ‘Nucleus’ does not have any field named ‘redshift_’, but if I do this instead:

class Nucleus: public Particle {
    Nucleus(double z) { redshift_ = z; }
};

it works. Why is this?

Sorry for the (probably) dumb question -- it's the first time I try to write a derived class in C++.

A1987dM
  • 11
  • 2
  • 4
    Have a look at this https://stackoverflow.com/questions/7405740/how-can-i-initialize-base-class-member-variables-in-derived-class-constructor – Pumkko Jan 15 '18 at 14:40
  • once the constructor of `Nucleus` is executed, the constructor for `Particle` has already run. Hence, `redshift_` already got default initialized and you cannot use the initializer list to initialize it – 463035818_is_not_an_ai Jan 15 '18 at 14:44
  • This is because in the second case, constructor of the Nucleus starts only after constructor of base class ends and redshift_ is created in scope, hence successful completion. When initialiser lists are used, redshift_ is still not created as base class's constructor is not yet called. – VishalTheBeast Jan 15 '18 at 17:08

0 Answers0