0 votes
134 views
in Programming by (98.9k points)
edited
Write a class in c++ to demonstrates the example of Single inheritance?

1 Answer

0 votes
by (98.9k points)
selected by
 
Best answer
#include <iostream>
using namespace std;

// Base class
class Shape {
 protected:
 int width;
 int height;

 public:
 void setWidth(int w) {
 width = w;
 }

 void setHeight(int h) {
 height = h;
 }
};

// Derived class
class Rectangle : public Shape {
 public:
 int getArea() {
 return (width * height);
 }
};

int main() {
 Rectangle rect;

 rect.setWidth(5);
 rect.setHeight(7);

 // Print the area of the object.
 cout << "Total area: " << rect.getArea() << endl;

 return 0;
}

Here's an example of a class in C++ that demonstrates single inheritance:

cpp#include <iostream>
using namespace std;

// Base class
class Shape {
 protected:
 int width;
 int height;

 public:
 void setWidth(int w){
 width = w;
 }

 void setHeight(int h){
 height = h;
 }
};

// Derived class
class Rectangle : public Shape {
 public:
 int getArea(){
 return (width * height);
 }
};

int main(){
 Rectangle rect;

 rect.setWidth(5);
 rect.setHeight(7);

 // Print the area of the object.
 cout << "Total area: " << rect.getArea() << endl;

 return 0;
}

This program defines two classes, Shape and Rectangle. Shape is the base class and Rectangle is the derived class, which inherits from Shape using the public keyword.

The Shape class has two protected member variables, width and height, and two public member functions, setWidth() and setHeight(), to set the values of these variables.

The Rectangle class is a derived class that inherits the Shape class. It has a public member function getArea() that calculates and returns the area of the rectangle using the width and height member variables inherited from the Shape class.

In the main() function, a Rectangle object is created and its setWidth() and setHeight() member functions are used to set the width and height of the rectangle. Then, the getArea() member function is called on the Rectangle object to calculate and display the area of the rectangle.

The output will be:

Total area: 35

This demonstrates single inheritance, where the Rectangle class inherits the Shape class, which serves as the base class for the Rectangle class.

Related questions

0 votes
1 answer 117 views
0 votes
1 answer 142 views
+1 vote
1 answer 204 views

Doubtly is an online community for engineering students, offering:

  • Free viva questions PDFs
  • Previous year question papers (PYQs)
  • Academic doubt solutions
  • Expert-guided solutions

Get the pro version for free by logging in!

5.7k questions

5.1k answers

108 comments

563 users

...