This is not homework, just some training exercises for my C++ class in order to get used to iheritance and stuff. So the first part of the exercise ask us to create a program which has one class name Rectangle and we should do the constructors getters and setters and find the area and perimeters.This part works fine. The second part of the exercise says to make a new class name Square which extends Rectangle and which has a constructor which will have as an argument the width of the square. Then the program should print the area and the perimeter.
#include <iostream>
using namespace std;
class Rectangular {
private:
int width;
int height;
public:
Rectangular () {
width = 5;
height = 5;
}
Rectangular (int w, int h) {
width = w;
height = h;
}
void setWidth (int w) {
width = w;
}
void setHeight (int h) {
height = h;
}
int getWidth () {
return width;
}
int getHeight () {
return height;
}
int getArea () {
return width*height;
}
int getPerimeter () {
return width+height;
}
};
class Square : public Rectangular{
public:
Square (int w) {
getWidth();
}
};
int main(int argc,char *argv[])
{
Rectangular a, b(10,12);
Square c(5);
cout << "Width for a: " << a.getArea() << " Perimeter for a: " << a.getPerimeter() << endl;
cout << "Width for b: " << b.getArea() << " Perimeter for b: " << b.getPerimeter() << endl;
cout << "Area for c: " << c.getArea() << " Perimeter for c: " << c.getPerimeter() << endl;
}
The program prints out
Width for a: 25 Perimeter for a: 10
Width for b: 120 Perimeter for b: 22
Area for c: 25 Perimeter for c: 10
For some reason c gets the values of a. Any thoughts?