문제

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.

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top