Search code examples
c++inheritancederived

Why I need to set a variable to some value in base class when I declare a derived class?


I dont understand why, when i try to create a object of a base class, i can, but only without declaring derived class, and when declare Derived i need to set argument value to "= 0" in base class constructor?

#include <cstdlib>

using namespace std;

class Base {
   public:
       int m_nValue;

       Base(int nValue=0) //<--- why here i need = 0 ?
           : m_nValue(nValue)
       {}
};

class Derived: public Base {
public:
    double m_dValue;

    Derived(double dValue) 
        : m_dValue(dValue)
    {}
};


int main(int argc, char** argv) {
  Base cBase(5); // use Base(int) constructor
  return 0;
}

Solution

  • No you don't. The problem is that when you subclass, you never give any value to the base class ctor, something like this:

    Derived(double dValue) : Base(0), m_dValue(dValue) {}
    

    So the compiler looks at the base class and search either: a ctor with no argument, or a ctor with default values (he doesn't look at the default ctor as defining a ctor removes the default ctor). Either:

    class Base {
    public:    
        int m_nValue;   
        Base() : m_nValue(0) {}
        Base(int nValue) : m_nValue(nValue) {}
    };
    

    or

    class Base {
    public:    
        int m_nValue;   
        Base(int nValue=0) : m_nValue(nValue) {}
    };