Why does c ++ implicitly call the default parent constructor?

advertisements

As far as I know, Constructors are not inherited, but when I tried out this code it throws an error about not having no appropriate default constructor

// Element.h
enum orientation{ up, down, left, right };

 class Element{
public:
    float get_value()  ;
    string get_unit();
    Point get_start_point();
protected:
    //Element(); // To prevent instatiation
    float value;
    const string unit;
    Point starting_point;
    orientation direction;

 };

class Resistance : public Element{
public:
    Resistance(Point,float,orientation);
private :
    const string unit = "Kohm";
};

From this error, I got that the parent class constructor is called implicitly. Note that error disappears when I declare constructor for Element.

//Element.cpp
float Element::get_value(){
return value;
};
string Element::get_unit(){
    return unit;
}
Point Element::get_start_point()
{
    return starting_point;
}
Resistance::Resistance(Point p, float value, orientation direction){

    Resistance::starting_point = p;
    Resistance::value = value;
    Resistance::direction = direction;
}

What's the thing that I am missing here ? Thanks


That's the way how OO works. In your example, because of inheritance, you declare that Resistance is also an Element, only a special kind of it.

It makes no sense to construct a child class without constructing the base; it would leave base in an inconsistent (or rather uninitialized) state.

Declare Element() as protected, to avoid instantiation of the base class, just as you did it in your example.