Calling constructor from another constructor?

I created three classes: Shape (base class) , Rectangle and Square. I tried to call Shape's constructor from Rectangle's and Square's constructors, but the compiler shows errors.

Here is the code:

class Shape{
public:
    double x;
    double y;
    Shape(double xx, double yy) {x=xx; y=yy;}
    virtual void disply_area(){
        cout<<"The area of the shape is: "<<x*y<<endl;
    }
};
class Square:public Shape{
public:
    Square(double xx){ Shape(xx,xx);}
    void disply_area(){
        cout<<"The area of the square is: "<<x*x<<endl;
    }
};
class Rectnagel:public Shape{
    public:
        Rectnagel(double xx, double yy){ Shape(xx,yy);}
    void disply_area(){
        cout<<"The area of the eectnagel is: "<<x*y<<endl;
    }
};
int main() {
    //create objects
    Square      sobj(3);
    Rectnagel   robj(3,4);
    sobj.disply_area();
    robj.disply_area();
    system("pause");;//to pause console screen, remove it if u r in linux
    return 0;
}

Any ideas or suggestion to modify the code?

Answers


To construct a base from a child you do the following

//constructor
child() : base()   //other data members here
{
     //constructor body
}

In your case

class Rectangle : public Shape{
    public:
        Rectangle(double xx, double yy) : Shape(xx,yy)
        {}

    void display_area(){
        cout<<"The area of the eectnagel is: "<<x*y<<endl;
    }
};

Need Your Help

Return different Dto using same repository method with Nhibernate

c# nhibernate

I have a Web API that request a GET method that can return based in the same parameters different results (Dtos) example: