1

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?

John Dibling
  • 99,718
  • 31
  • 186
  • 324
Aan
  • 12,247
  • 36
  • 89
  • 150
  • possible duplicate of [Explicitly calling a constructor in C++](http://stackoverflow.com/questions/827552/explicitly-calling-a-constructor-in-c) – Tony Dec 01 '11 at 22:15
  • possible duplicate of [C++ superclass constructor calling rules](http://stackoverflow.com/questions/120876/c-superclass-constructor-calling-rules) – BЈовић Dec 01 '11 at 22:18
  • Instead of commenting your `system("pause";)` hack, replace it with something portable. See http://www.gidnetwork.com/b-61.html. – Fred Larson Dec 01 '11 at 22:32

2 Answers2

7

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;
    }
};
111111
  • 15,686
  • 6
  • 47
  • 62
4

This is the correct way to do it:

class Square:public Shape{
public:
    Square(double xx) : Shape(xx,xx){}
    void disply_area(){
        cout<<"The area of the square is: "<<x*x<<endl;
    }

};

Look up the superclass constructor calling rules.

Community
  • 1
  • 1
BЈовић
  • 62,405
  • 41
  • 173
  • 273