Search code examples
c++inheritanceconstructorconstantsinitialization-order

C++ passing const value of derived class to constructor of base unexpected behavior


I assume this is fairly basic, but I couldn't find any source here.

A derived class contains initialization information which needs to be passed to the base class. In this case it is a memory reservation.

class Derived: public Base
{
private:
  const unsigned short memorySize= 100;    
public:  
  inline Derived() : Base(memorySize) {}
  void DoStuff();
};

This fails miserably. I expect the base constructor is called before the derived constructor, and memorySize is only assigned when the derived constructor is being called.

#define memorySize 100

class Derived: public Base
{
private:

public:  
  inline Derived() : Base(memorySize) {}
  void DoStuff();
};

This works as expected.

My questions: Is my assumption that memorySize in the first example has not yet been initialized at the time the base constructor is being called, or is something else happening here?

I have learned that #define for constants are undesirable in C++, and it's highly preferable to use const values. Is this an exception to this rule, or is there a more proper way to deal with this situation?


Solution

  • The two examples are entirely incomparable. In the first example, every instance of Derived gets its own copy of memorySize. As you guessed, the constructor of Derived takes care of that.

    You don't want that at all. There's only one constant for the class, not a separate constant for every instance. That's written as

    class Derived: public Base
    {
    private:
      static const unsigned short memorySize = 100;