How to inherit attributes and methods from one class to another in C++ ?


In C++, inheritance is a mechanism that allows a new class to be based on an existing class. The new class is called the derived class, and the existing class is called the base class. The derived class inherits all the attributes and methods of the base class, and can also add its own attributes and methods.

There are two types of inheritance in C++: public and private. Public inheritance means that the public and protected members of the base class become public and protected members of the derived class, respectively. Private inheritance means that the public and protected members of the base class become private members of the derived class.

Here is an example of how to inherit attributes and methods from one class to another in C++ using public inheritance:

// 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);
    cout << "Area of rectangle: " << rect.getArea() << endl;
    return 0;
}

In this example, the Shape class is the base class and the Rectangle class is the derived class. The Rectangle class inherits the setWidth() and setHeight() methods from the Shape class using public inheritance. It also adds its own method getArea() which calculates the area of the rectangle.

Another way to inherit attributes and methods from one class to another in C++ is using private inheritance. Here is an example:

// 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 Square: private Shape {
public:
    int getArea() {
        return (width * width);
    }
    void setSide(int s) {
        setWidth(s);
        setHeight(s);
    }
};

int main() {
    Square sq;
    sq.setSide(5);
    cout << "Area of square: " << sq.getArea() << endl;
    return 0;
}

In this example, the Square class is the derived class and it inherits the setWidth() and setHeight() methods from the Shape class using private inheritance. It also adds its own method getArea() which calculates the area of the square. The setSide() method is used to set the width and height of the square to the same value.



About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.