Home > Backend Development > C++ > body text

C++ program to test inheritance through triangle class

PHPz
Release: 2023-08-26 09:57:13
forward
914 people have browsed it

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();
}
Copy after login

Input

Isosceles trg;
trg.isosceles();
trg.description();
trg.triangle();
Copy after login

Output

This is an isosceles triangle
There are two sides are equal in an isosceles triangle
This is a triangle
Copy after login

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template