user1681664
user1681664

Reputation: 1811

Nested Classes variable calls

I want to go from this: enter image description here

To this: enter image description here

How would I do this? How would the functions of subclasses square and rectangle know to use the variable of the parent class shape?

How would I set length and width from main?

#include <iostream>
#include <cmath>
using namespace std;

class SHAPES
{
      public:
      class SQUARE
      {
            int perimeter(int length, int width)
            {
                return 4*length;
            }
            int area(int length, int width)
            {
                return length*length;
            }
      };
      public:
      class RECTANGLE
      {
            int perimeter(int length, int width)
            {
                return 2*length + 2*width;
            }
            int area(int length, int width)
            {
            return length*width;
            }
      };

};

Upvotes: 0

Views: 682

Answers (2)

Andy Prowl
Andy Prowl

Reputation: 126412

Those are not subclasses (i.e. derived classes), but rather nested classes (as the title of your question says).

I don't think I would answer your real question if I were to tell you how to make those variables visible in nested classes. Based on what I can understand from the names of your classes, you should rather use inheritance to model the IS-A relation between them:

class SHAPE
{
public: // <-- To make the class constructor visible
    SHAPE(int l, int w) : length(l), width(w) { } // <-- Class constructor
    ...
protected: // <-- To make sure these variables are visible to subclasses
    int length;
    int width;
};

class SQUARE : public SHAPE // <-- To declare public inheritance
{
public:
    SQUARE(int l) : SHAPE(l, l) { } // <-- Forward arguments to base constructor
    int perimeter() const // <-- I would also add the const qualifier
    {
        return 4 * length;
    }
    ...
};

class RECTANGLE : public SHAPE
{
    // Similarly here...
};

int main()
{
    SQUARE s(5);
    cout << s.perimeter();
}

Upvotes: 1

Yousf
Yousf

Reputation: 3997

I recommend other (better?!) format:

class Shape
{
protected:
    int length,width;
public: 
    Shape(int l, int w): length(l), width(w){}
    int primeter() const
    {
        return (length + width) * 2;
    }
    int area() const
    {
        return length * width;
    }
};

class Rectangle : public Shape
{
public
    Rectangle(int l, int w) : Shape(l,w){}
};

class Square : public Shape
{
public:
    Square(int l): Shape(l,l){}
};


int main()
{
    Rectangle r(5,4);
    Square s(6);

    r.area();
    s.area();
}

Or use interface with virtual function.

Upvotes: 1

Related Questions