Reputation: 63
I'm trying to understand constructors and inheritance in C++ by doing the following exercise:
Write a program that defines a shape class with a constructor that gives value to width and height. The define two sub-classes triangle and rectangle, that calculate the area of the shape area (). In the main, define two variables a triangle and a rectangle and then call the area() function in this two variables.
My attempt writing a constructor:
#include <iostream>
using namespace std;
class Shape
{
protected:
double width, height;
public:
// Define constructor
Shape(double newWidth, double newHeight):
width{newWidth}, height{newHeight} {}
// Define getters
double getWidth() const
{
return width;
}
double getHeight() const
{
return height;
}
};
class Rectangle: public Shape
{
public:
double area()
{
return (width*height);
}
};
class Triangle: public Shape
{
public:
double area()
{
return (width*height)/2;
}
};
int main ()
{
Rectangle rect(5.0,3.0);
Triangle tri(2.0,5.0);
cout << rect.area() << endl;
cout << tri.area() << endl;
return 0;
}
Gives the following error:
no instance of constructor "Rectangle::Rectangle" matches the argument list -- argument types are: (double, double)
I think the error comes from how I instantiate both rect
and tri
but I can't seem to solve the issue. Any suggestions?
Upvotes: 6
Views: 1395
Reputation: 2412
As you instanciate your rect
and tri
variables with two arguments (Triangle(double, double)
and Rectangle(double,double)
), thus you need to define these constructors with two arguments in your derived classes. Currently, you have not defined constructor with (double,double)
arguments for your derived classes Triangle
and Rectangle
.
Your error comes from the fact that, when the body of the derived class constructor is run, it first invokes the default (no-argument) constructor for its base class.
As you already have a Shape(double,double)
constructor with arguments and have not defined a no-argument Shape()
constructor, then it fails to compile.
To solve your error, you need to use Initialization lists
of your Triangle
and Rectangle
constructors, which allow you to choose which base class constructor is called and what arguments that constructor should receive. More document here and here.
Here is my code attempt
class Rectangle: public Shape
{
public:
//create a Triangle constructor and call base class with its arguments
Rectangle(double lWidth, double l_Height):Shape(lWidth,l_Height)
{
}
double area()
{
return (width*height);
}
};
class Triangle: public Shape
{
public:
//create a Triangle constructor and call base class with its arguments
Triangle(double lWidth, double l_Height): Shape(lWidth,l_Height)
{
}
double area()
{
return (width*height)/2;
}
};
Upvotes: 0
Reputation: 468
Constructors are not inherited. If you want to inherit the constructor you can:
class Rectangle : public Shape
{
public:
using Shape::Shape;
// etc.
};
Upvotes: 12