0

Hello I need help in accessing and displaying the results of the three classes derived from the base class. They are private and I'm having difficulty in doing so. I have searched and tried on my own from what I understand about set and get but it's not working.

#include<iostream>
using namespace std;

class Shape
{
private:
    double height, width;
    double radius;
public:
    void set_data(int i)
    {
        height, width, radius = i;

    }
    void get_data()
    {
        cin>>height>>width>>radius;
    }
    virtual void display_area()=0;
};

class Triangle: public Shape
{
public:
    void display_area()
    {
        cout<<"\nArea of triangle = "<<(height*width)/2;
    };
};

class Rectangle : public Shape
{
public:
    void display_area()
    {
        cout<<"\nArea of rectangle = "<<height*width;
    }
};

class Circle: public Shape
{
public:
    void display_area()
    {
        cout<<"\nArea of circle = "<<3.14*radius*radius;
    }
};
int main()
{
    Triangle t;
    Shape *st = &t;
    Rectangle r;
    Shape *sr = &r;
    Circle c;
    Shape *sc = &c;
    cout<<"Enter height and width: ";

    t.set_data(2,6);
    r.set_data(9,10);
    c.set_data(3,6,4);
    cout<<t.get_data()<<r.get_data()<<c.get_data();


    return 0;
}
    t.set_data(2,6);
    r.set_data(9,10);
    c.set_data(3,6,4);
    cout<<t.get_data()<<r.get_data()<<c.get_data();

I understand to access a private class within a public one will bring errors so I tried the whole set and get but I think I'm still doing it wrong and I need some guidance/assistance.

mch
  • 9,424
  • 2
  • 28
  • 42
YK 0014
  • 9
  • 2
  • 1
    You can't access private members of a parent class. Make them protected instead. – tkausl Dec 28 '22 at 10:57
  • 2
    "All shapes have a width, a height, and a radius." Really? – molbdnilo Dec 28 '22 at 11:14
  • 4
    Despite what you believe, `height, width, radius = i;` does not assign the same value to three variables. – molbdnilo Dec 28 '22 at 11:16
  • 3
    I think you should start with a single class, no inheritance, and get that working. There are a few fundamental misunderstandings in that code that you need to get past. – molbdnilo Dec 28 '22 at 11:25

1 Answers1

0

Your set_data function takes only one integer. For the circle you are trying to call it with three arguments.

The general class Shape has a radius as an attribute. It makes no sense as there are derived classes that don't use it.

Also. Your get_data function will ask the user to write some numbers with the keyboard. It is a function that returns nothing. So when you write cout << t.get_data() nothing will be printed as cout gets nothing from get_data.

You better treat Shape as an interface. That is: force all the derived classes to implement set_data and display_area, but don't implement any of this logic in the base class as it is too general.

Jorge Luis
  • 813
  • 6
  • 21