The goal of my program is to use a class with private members length and width and public functions to calculate the area and perimeter. I am supposed to use a constructor and use the functions to calculate and display the area and perimeter of a rectangle with length 7 and width 9. My program runs successfully, but I am afraid I did not access the private members the right way. If i delete the private part of the class, the program runs the same. Any advice on if I am doing something wrong would be appreciated.
#include <iostream>
using namespace std;
class Plot
{
private:
int length;
int width;
public:
int area(int, int);
int boundary(int, int);
};
int Plot::area(int x, int y) // constructor
{
return x*y;
}
int Plot::boundary(int x, int y) // constructor
{
return 2*(x+y);
}
int main()
{
Plot Field;
int x = 7;
int y = 9;
cout << "Length of the field is " << x << " and width of the field is " << y << endl;
cout << "Area is: " << Field.area(x,y) << endl;
cout << "Length of boundary is: " << Field.boundary(x,y) << endl;
There's a few major problems here. The functions you have labeled as constructors are not constructors at all. A constructor is a function that gets called when an instance of your class is created (like the Plot Field; statement). Its purpose is to initialize variables of the class. You need to make an actual constructor that will do just that, like so...
1 2 3 4 5
Plot::Plot (int l, int w) // Note that constructors do NOT have a return type
{
length = l;
width = w;
}
Now that you have this, you can change your other functions to work properly. They should not accept any arguments, but instead work off of the data in the width and length fields. So for example, area should look like...
1 2 3 4
int Plot::area()
{
return length*width;
}
Note that you do not need the x and y variables you declared in main. You can pass the values into the constructor of the Plot class when you create it, like this...
Plot Field(7, 9);
Lastly, please put your code in code blocks by putting ["code"] at the beginning of your code and ["/code"] at the end (without the quotes of course).
Thank you everyone for the help. I was way off with my constructors (this is my first week using them), but I feel like I have a better idea on how and when to use them now.