0% found this document useful (0 votes)
32 views1 page

Base and Derived Class

The document explains the concept of base and derived classes in object-oriented programming, highlighting that a derived class can inherit from multiple base classes using a class derivation list. It provides an example with a base class 'Shape' and a derived class 'Rectangle' that calculates the area. The code snippet demonstrates how to set dimensions and compute the area of a rectangle, resulting in an output of 'Total area: 35'.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views1 page

Base and Derived Class

The document explains the concept of base and derived classes in object-oriented programming, highlighting that a derived class can inherit from multiple base classes using a class derivation list. It provides an example with a base class 'Shape' and a derived class 'Rectangle' that calculates the area. The code snippet demonstrates how to set dimensions and compute the area of a rectangle, resulting in an output of 'Total area: 35'.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 1

Base and Derived Classes

A class can be derived from more than one classes, which means it can inherit data
and functions from multiple base classes. To define a derived class, we use a class
derivation list to specify the base class(es). A class derivation list names one or
more base classes and has the form −

class derived-class: access-specifier base-class


Where access-specifier is one of public, protected, or private, and base-class is
the name of a previously defined class. If the access-specifier is not used, then
it is private by default.

Consider a base class Shape and its derived class Rectangle as follows −

Live Demo
#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(void) {
Rectangle Rect;

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

// Print the area of the object.


cout << "Total area: " << Rect.getArea() << endl;

return 0;
}
When the above code is compiled and executed, it produces the following result −

Total area: 35

You might also like