I've looked all over and haven't found an answer on this that I can understand. I included my code (most of it, anyway.) Obviously, I'm trying to make class Square a subclass of class Rectangle. However, I can't get my display() method to work properly in the derived class. The function calls within it keep reading the dimensions from the original Rectangle class. Isn't there a way I can "virtualize" something and get the inner functions to read the right data? What am I doing wrong? (Sorry to put so much code up. I trimmed it down but I wanted to make sure y'all had all the details you'd need.)
#include <iostream>
using namespace std;
class Rectangle //class declaration
{
private:
double base;
double height;
public:
Rectangle(double base = 5.00, double height = 4.00); //constructor
double area();
void display();
};
//Rectangle methods
Rectangle::Rectangle(double b, double h)
{
base = b;
height = h;
}
double Rectangle::area()
{
double a;
a = (base * height);
return a;
}
void Rectangle::display()
{
cout << "\nBase: " << base;
cout << "\nheight: " << height;
cout << "\narea: " << area();
}
class Square : public Rectangle //class declaration
{
private:
double base;
double height;
public:
Square(double base = 3.00); //constructor
void display();
};
//Square methods
Square::Square(double b)
{
base = b;
height = b;
}
void Square::display()
{
cout << "\nBase: " << base;
cout << "\narea: " << Square::area(); //tried a bunch of things here
}
//=================main function============================
int main()
{
Rectangle rect1( 7.00000, 9.00000 );
Rectangle rect2; //use default constructor
Square squA; //use default constructor
Square squB( 5.50 );
//rect1 and 2 display fine
cout << "Rectangle 1 Characteristics";
rect1.display();
cout << "\n\nRectangle 2 Characteristics";
rect2.display();
//but these two return the wrong data. The base dimensions display
//properly but the areas are the same as a default rectangle
cout << "\n\nSquare A Characteristics";
squA.display();
cout << "\n\nSquare B Characteristics";
squB.display();
cin.get();
return 0;
}