9.5K
Table of Contents
C++ Program to calculate the area using classes in two ways, one with “using one class and one object” and another with “using one class ,two objects“.
Using one class and one object.
#include<iostream>
using namespace
class Rectangle {
int width, height;
public
void set_values (int,int);
int area() {return width*height;}
};
void Rectangle::set_values ( int x, int y) {
width = x;
height = y;
}
int main () {
Rectangle rect;
rect.set_values (3,4);
cout<<"area: "<< rect.area();
return 0;
}
Output
area: 12
Using one class ,two objects
#include<iostream>
using namespace std;
class Rectangle
{
int width, height;
public:
void set_values (int, int);
int area ()
{
return width * height;
}
};
void
Rectangle::set_values (int x, int y)
{
width = x;
height = y;
}
int
main ()
{
Rectangle rect, rectb;
rect.set_values (3, 4);
rectb.set_values (5, 6);
cout << "rect area: " << rect.area () << endl;
cout << "rectb area: " << rectb.area () << endl;
return 0;
}
Output
rect area: 12
rectb area: 30