Use of this pointer to find the Area of Right angel triangle:
1. Declare a class Triangle.
2. Create a constructor which sets the length and width of triangle.
3. Calculate the Area of triangle in function Area (), return the reference using this pointer.
4. Make another function Compare () which compares two calculated Areas and prints the
larger area, again return the reference using this pointer.
5. Use two different objects in main for calculating two different areas pass them to compare
Function for comparison.
#include<iostream>
using namespace std;
class Triangle{
private:
int base, height;
public:
Triangle(){
}
Triangle(int b, int h){
base = b;
height = h;
}
double area;
double Area(){
this->area = 0.5* (this-> base * this->height) ;
}
double max;
void Compare(double area1, double area2){
this->max = area1;
if(area2 > area1){
this->max = area2;
}
cout<<"The larger area is:\t"<<this->max<<endl;
}
};
int main(){
Triangle t1(4,9);
Triangle t3(7,2);
Triangle t;
cout<<t3.Area()<<endl;
double area1 = t1.Area();
double area2 = t3.Area();
t.Compare(area1 ,area2);
}
Comments
Leave a comment