OBJECT-ORIENTED PROGRAMMING (C++)
We are learning about the following things by this example:
- Classes in C++
- Constructors
- Parameterized Constructors
- Generic Data Input
Task Example:
QUESTION:
Write a program to print the area of a rectangle and
perimeter of the rectangle by creating a class named 'Area' taking the values
of its length and breadth as parameters of its constructor and having a
function named 'returnArea' which returns the area of the rectangle.
Length and breadth of
the rectangle are entered through keyboard.
·
Write parameterized constructor (with input validation).
·
Write separate setter functions for each attribute to set value (with input
validation).
·
Write separate getter functions for each attribute to get value.
Solution
#include
<iostream>
using namespace std;
class Area
{
public:
int length, breadth;
Area()
{
length = 0;
breadth = 0;
}
Area(int l, int b)
{
length = l;
breadth = b;
}
void Setlength(int l)
{
length = l;
}
void Setbreadth(int b)
{
breadth = b;
int Getlength()
{
return length;
}
int Getbreadth()
{
return breadth;
}
void showarea()
{
int result;
result = length*breadth;
cout << "Area
of Rectangle: " << result << endl;
}
void showperimeter()
{
int perimeter;
perimeter = 2 * (length + breadth);
cout <<
"Perimeter of Rectangle is: " << perimeter <<
endl<<endl;
}
};
int main()
{
Area obj;
obj.Setlength(8);
obj.Setbreadth(5);
obj.showarea();
obj.showperimeter()
system("pause");
return 0;
}
That's
exactly what today's post is all about. We hope you'll like it. You can also
message us to see more posts, and if you like it, be sure to share it with your
friends. Thank you very much for reading.
-----------------------------------------------------------------------------------
0 Comments