Classes are user created data types. Instead of declaring separate data types for similar tasks, a class can be created having data variables and functions which can be reused or inherited in the main function. A class is created using keyword class. Data variables are called the data members and functions are called the member functions.
To reuse or inherit the data types and functions of a class an object is created in the main function. An object is a name which is used with the class name to inherit the properties of a class. A dot operator (.) is used to access the data members and member functions.
The following program shows a class ‘Area‘. ‘triangle’ and ‘rectangle’ are the objects. Data members ‘length’ and ‘breadth’ are accessed by using the (.) operator.
#include<iostream>
using namespace std;
class Area {
public:
float length;
float breadth;
};
int main() {
Area triangle, rectangle;
triangle.length = 5;
triangle.breadth = 10;
rectangle.length = 20;
rectangle.breadth = 25;
cout<<"The length of triangle is "<<triangle.length<<endl;
cout<<"The breadth of triangle is "<<triangle.breadth<<endl;
cout<<"\nThe length of rectangle is "<<rectangle.length<<endl;
cout<<"The breadth of rectangle is "<<rectangle.breadth;
return 0;
}
Output:
The length of triangle is 5
The breadth of triangle is 10
The length of rectangle is 20
The breadth of rectangle is 25
The following program shows member function of class accessed by using dot operator on objects.
#include<iostream>
using namespace std;
class Area {
public:
float length;
float breadth;
float areaTriangle() {
return 0.5*length*breadth;
}
float areaRectangle() {
return length*breadth;
}
};
int main() {
Area triangle, rectangle;
triangle.length = 5;
triangle.breadth = 10;
rectangle.length = 20;
rectangle.breadth = 25;
cout<<"The area of triangle is "<<triangle.areaTriangle()<<endl;
cout<<"The area of rectangle is "<<rectangle.areaRectangle();
return 0;
}
Output:
The area of triangle is 25
The area of rectangle is 500