Reputation: 12890
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?
Upvotes: 1
Views: 506
Reputation: 64203
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.
Upvotes: 4
Reputation: 16148
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;
}
};
Upvotes: 7