Home  >  Article  >  Backend Development  >  C++ program to test inheritance through triangle class

C++ program to test inheritance through triangle class

PHPz
PHPzforward
2023-08-26 09:57:13912browse

C++ program to test inheritance through triangle class

Suppose we want to create a Triangle class and another subclass called Isosceles. The Triangle class has a function for printing that the object is of type triangle, while Isosceles has two functions for displaying that it is an isosceles triangle and a description. We also need to call the parent class function through the Isosceles class object. Without proper input, we just call the function in the appropriate way.

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

This is an isosceles triangle

In an isosceles triangle there are two sides that are equal

This is an isosceles triangle

To solve this problem we will follow the following steps :

  • Define the first Triangle class, which contains the public/protected function triangle()

  • Define the Isosceles class, using public inheritance , in which there are two methods called isosceles() and description()

Example

Let us look at the following implementation for 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

The above is the detailed content of C++ program to test inheritance through triangle class. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete