C++ program to test inheritance through triangle class

C++Server Side ProgrammingProgramming

Suppose we want to make one Triangle class and another child class called Isosceles. The triangle class has a function that prints that the object is of type triangle, and Isosceles has two functions to show that it is an isosceles triangle and one description. We also need to call the parent class function through Isosceles class object. There is no such proper input, we just call functions in proper way.

So, if the input is like define an object called trg, then call trg.isosceles(), trg.description(), trg.triangle()., then the output will be

This is an isosceles triangle

There are two sides are equal in an isosceles triangle

This is a triangle

To solve this, we will follow these steps −

  • Define the first Triangle class with public/protected function triangle()

  • Define Isosceles class with public inheritance where two methods are present called isosceles() and description()

Example

Let us see the following implementation to get better understanding −

#include <iostream>
using namespace std;
class Triangle{
    public:
       void triangle(){
           cout<<"This is a triangle" << endl;
       }
};
class Isosceles : public Triangle{
    public:
       void isosceles(){
          cout<<"This is an isosceles triangle" << endl;
       }
       void description(){
          cout<<"There are two sides are equal in an isosceles triangle" << endl;
       }
};
int main(){
    Isosceles trg;
    trg.isosceles();
    trg.description();
    trg.triangle();
}

Input

Isosceles trg;
trg.isosceles();
trg.description();
trg.triangle();

Output

This is an isosceles triangle
There are two sides are equal in an isosceles triangle
This is a triangle
raja
Published on 07-Oct-2021 08:29:55
Advertisements