Domanda

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

È stato utile?

Soluzione

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.

Altri suggerimenti

There are two issues in your question:

  1. Each Resistance contains an Element subobject which needs to be constructed. After all, you can subsequently assign a Resistance* to an Element*. Just think about what this means for a second, and it should be clear that a constructor of Element must be called.

  2. If you declare a default constructor in a class, you declare to the compiler that you are not satisfied with the default constructor that it would normally generate. So, you need to actually supply an implementation for it.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top