In C++, inheritance is a feature that allows one class to inherit the properties and behavior of another class. The class that is being inherited from is called the base class, and the class that is inheriting is called the derived class.
To define a derived class in C++, we use the following syntax:
class DerivedClass : access_base_class BaseClass { // class members and functions };
Here, `DerivedClass` is the name of the derived class, `BaseClass` is the name of the base class, and `access_base_class` specifies the access level for the base class members in the derived class. The access level can be one of `public`, `protected`, or `private`.
Public inheritance is the most common type of inheritance, and it means that the public members of the base class are accessible from the derived class. Protected inheritance means that the public and protected members of the base class are accessible from the derived class as protected members. Private inheritance means that the public and protected members of the base class are accessible from the derived class as private members.
Here’s an example of a base class:
class Shape { public: void setWidth(int w) { width = w; } void setHeight(int h) { height = h; } protected: int width; int height; };
And here’s an example of a derived class:
class Rectangle : public Shape { public: int getArea() { return width * height; } };
In this example, the `Rectangle` class inherits from the `Shape` class using public inheritance. This means that the `setWidth()` and `setHeight()` functions of the `Shape` class are accessible from the `Rectangle` class as public members, and the `width` and `height` member variables of the `Shape` class are accessible from the `Rectangle` class as protected members.
The `Rectangle` class defines a new member function `getArea()` that calculates the area of the rectangle using the `width` and `height` member variables inherited from the `Shape` class.
Access control in derived classes is important because it determines which members of the base class are accessible from the derived class. Public members of the base class are always accessible from the derived class, regardless of the access level specified in the inheritance declaration. Protected members of the base class are accessible from the derived class as protected members, and private members of the base class are not accessible from the derived class.
It’s important to use access control in a way that makes sense for the design of the classes, and to carefully consider the relationships between the base class and the derived class. In general, it’s a good idea to make member variables private and provide public member functions to access and modify them, to ensure that the class maintains proper encapsulation and data hiding.