inheritance example in C plus plus
#include <iostream>
using namespace std;
// Base class
class Shape {
public:
void setWidth(int w) {
width = w;
}
void setHeight(int h) {
height = h;
}
protected:
int width;
int height;
};
// 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;
}
Explanation:
- #include <iostream>
: Includes the input/output stream library, allowing the program to perform input and output operations.
- using namespace std;
: Enables the use of entities in the standard C++ library (such as cout and endl) without specifying the namespace.
- class Shape { ... };
: Defines a base class named Shape
. It contains setWidth()
and setHeight()
functions to set the width and height of the shape, respectively.
- protected:
: Indicates that the width
and height
member variables are accessible within this class and its derived classes.
- class Rectangle : public Shape { ... };
: Defines a derived class Rectangle
that inherits publicly from the Shape
class. It does not add any new members but inherits the width
and height
variables from Shape
.
- int getArea() { ... }
: Defines a member function getArea()
in the Rectangle
class to calculate and return the area of the rectangle using the inherited width
and height
.
- main() { ... }
: The main function where the program execution starts.
- Rectangle Rect;
: Creates an object Rect
of type Rectangle
.
- Rect.setWidth(5);
: Sets the width of the rectangle object Rect
to 5 using the setWidth()
function inherited from the Shape
class.
- Rect.setHeight(7);
: Sets the height of the rectangle object Rect
to 7 using the setHeight()
function inherited from the Shape
class.
- cout << "Total area: " << Rect.getArea() << endl;
: Calculates and prints the total area of the rectangle object Rect
using the getArea()
function inherited from the Rectangle
class.
The example demonstrates inheritance in C++ where the Rectangle
class inherits the properties and functions of the Shape
class, allowing it to calculate the area based on width and height inherited from the base class.