Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

using a class n times with a for loop c++

I’m trying to learn classes, so here I want to create n-number Triangle and Rectangle types, input a,b,c, also input from user and then cout them.. im trying to get n-number of Triangle and Rectangle with for loop but at the end I get print only the biggest S() and P() which user had entered.. for example if I user says n=2 so there will be 2 Triangles and 2 Rectangles .. Rectangle a1 = 1, b1 = 2; Rectangle a2 = 3, b2 = 4.. ill get s() output s = 12 and again s = 12 instead of s = 2 and s = 12
enter image description here
Im sorry for the worst description ever ..

    class Rectangle
{
protected:
    int a, b;
    
    virtual double S()
    {
        return a*b;
    }
    
    virtual double P()
    {
        return (2*a) + (2*b);
    }
    
public:
    Rectangle (int aa, int bb) {a = aa; b = bb;}
    
    virtual void Input()
    {
        cout << " enter a: "; cin >> a;
        cout << " enter b: "; cin >> b;
        cout << endl;
    }
    
    virtual void Print()
    {
        cout << " Rectangle S = " << S() << endl;
        cout << " Rectangle P = " << P() << endl;
        cout << endl;
    }
};

    int main()
{
    int n;
    cout << " enter number of triangles and rectangles... "; cin >> n;
    cout << endl;
    Rectangle rectangle(1, 1);
    Triangle triangle(1,1,1);
    
    for (int i=0; i<n; i++)
    {
        rectangle.Input();
    }

        for (int i=0; i<n; i++)
    {
        rectangle.Print();
    }
    

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You are overwriting the same variable every time you call Input(). Instead, create a vector of rectangles.

#include <vector>

class Rectangle {
    // ...
};

int main()
{
    // ...
    
    std::vector<Rectangle> rectangles(n);    
    for (int i=0; i<n; i++)
    {
        rectangles[i].Input();
    }

    for (int i=0; i<n; i++)
    {
        rectangles[i].Print();
    }
}

You need to add a default constructor for Rectangle so that you can use it with vector.

For example:

Rectangle() { a = 0; b = 0; }
Rectangle(int aa, int bb) {a = aa; b = bb;}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading