WEB DEVELOPER SITE
PYTHONPHP7JAVA
 

C++ Inheritance


Inheritance is one of the most important concepts of object-oriented programming(OOP). Inheritance allows us to define a class based on another class. This facilitates greater ease in creating and maintaining an application.
The idea of inheritance implements the is a relationship. For example, mammal IS-A animal, dog IS-A mammal, hence dog IS-A animal as well.

Syntax

Son class from the Father class.
class Son : public Father
{
 public: 
  Son() {};
};

Run example»

Base and Derived Classes

Consider a base class Shape and its derived class Rectangle as follows Where access-specifier is one of public, protected, or private, and base-class is the name of a previously defined class.
#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;
}
  public, protected, or private, and base-class is the name of a previously defined class.
Run example»

all public members of the Father class become public members of the Son class.

A derived class inherits all base class methods with the following exceptions:

  • Constructors, destructors
  • Overloaded operators