0% found this document useful (0 votes)
8 views2 pages

C++ Inheritance Example with Shapes

The document contains C++ code that demonstrates inheritance through a series of classes: Shape, Polygon, Rectangle, Triangle, and Square. Each class has a display() method that outputs a message indicating its relationship to the shape hierarchy. The main function creates objects of each class and calls their display() methods to show the inheritance structure.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views2 pages

C++ Inheritance Example with Shapes

The document contains C++ code that demonstrates inheritance through a series of classes: Shape, Polygon, Rectangle, Triangle, and Square. Each class has a display() method that outputs a message indicating its relationship to the shape hierarchy. The main function creates objects of each class and calls their display() methods to show the inheritance structure.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

#include <iostream>

using namespace std;

// Step 1: Define a base class Shape

class Shape {

public:

void display() {

cout << "This is a shape" << endl;

};

// Step 2: Define a derived class Polygon inheriting from Shape

class Polygon : public Shape {

public:

void display() {

cout << "Polygon is a shape" << endl;

};

// Step 3: Define two more classes Rectangle and Triangle inheriting from Polygon

class Rectangle : public Polygon {

public:

void display() {

cout << "Rectangle is a polygon" << endl;

};

class Triangle : public Polygon {

public:

void display() {

cout << "Triangle is a polygon" << endl;


}

};

// Step 4: Define a class Square inheriting from Rectangle

class Square : public Rectangle {

public:

void display() {

cout << "Square is a rectangle" << endl;

};

// Step 5: Create an object of each class and call the display() function

int main() {

Shape shapeObj;

Polygon polygonObj;

Rectangle rectangleObj;

Triangle triangleObj;

Square squareObj;

[Link]();

[Link]();

[Link]();

[Link]();

[Link]();

return 0;

You might also like