Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No Instance of Constructor "Class:Class" matches argument list

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?

like image 735
CosmicPeanutButter Avatar asked Apr 06 '21 10:04

CosmicPeanutButter


1 Answers

Constructors are not inherited. If you want to inherit the constructor you can:

class Rectangle : public Shape
{
public:
  using Shape::Shape;

  // etc.
};
like image 168
SparkyPotato Avatar answered Nov 15 '22 01:11

SparkyPotato