Header Ads Widget

Base class and Derived class: Inheritance

 Base class and Derived class:


            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 −

Program Example :--

#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);


Object Oriented Programming : Grade 10 97

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