0
votes

I'm trying to pass a variable from parent class to it's child class. The code does compile, but keeps giving me the result; 0. When I hardcode the value in the base constructor inside the child class, it does give me the wanted result.

Parent class.h:

class Parent{
 float price;

public:
 Parent(float price)
}

Parent class.cpp:

 #include "Parent.h"

 Parent::Parent(float price){
 this->price = price;
 }

Child class.h:

 class Child : Parent{
 const float price = 0.29;

 public:
 Child();
 }

Child class.cpp:

#include "Child.h"

Child::Child() : Parent(price){
}

How can I make it so the var inside the child class can be used in the constructor of the base class?

2
It does not sadly enough, when I type Child::Child() : Parent(0.29){} it works.. - MrEmper

2 Answers

3
votes

Note that the initialization order is:

The order of member initializers in the list is irrelevant: the actual order of initialization is as follows:

...

  • 2) Then, direct base classes are initialized in left-to-right order as they appear in this class's base-specifier list

  • 3) Then, non-static data members are initialized in order of declaration in the class definition.

...

The base subobjects are always initialized before data members; that means when you're trying to pass the data member Child::price to the constructor of the base class Parent, it's not initialized yet.

0
votes

If you don't mind using static you can do the following:

// Child.h
class Child : Parent {
    static const float price;

 public:
    Child();
};
// Child.cpp
const float Child::price = 0.29;

This code will work as intended.