Last Updated:

Basic principles of inheritance in C++

If you are using an inheritance mechanism, consider all the abstractions of your object model and place those that can be reused in the base classes at as high a level as possible. You can add and modify properties in more specialized derived classes that inherit the standard behavior of the base classes. Inheritance makes it easier to reuse and extensibility your code. In addition, the derived class may contain an interface that is more appropriate for the members of the base class.

Let's look at the Reservable base class and the Hotel class that derives from it. All reservations have some common properties, such as object identifier (ID), capacity, and cost. Each individual type of reserved object has its own unique properties. For example, in the class of the hotel there are attributes City (City) and Hotel-Name (Name of the hotel).

Inheritance Syntax in Managed C++

Inheritance in managed C++ is implemented in this way: in the class statement of a derived class, the name of the base class is specified through a colon. The HotelBroker.h file in the CaseStudy folder shows how the Hotel class is derived from the Reservable base class.

public _gc class Hotel: public Reservable
// garbage collector class - Hotel:Reservable
{
};

The Hotel class automatically inherits all fields of the Reservable class and contains its own City and NotelName fields.

Make changes to the interface of existing class members

Base class members, unit idcapacitycost, are intended for internal use and should not be publicly available. The Hotel class contains public members of Hotel IdNumberRooms, and Rate that users have read-only access to. When we implement a property in this way, we can choose a more specific name, such as NumberRooms, instead of an abstract name, such as capacity, which is used in the base class.

Calling Base Class Constructors

If your derived class has a constructor with parameters, you might want to pass some of those parameters to the base class constructor. In C++, you can call the constructor of a base class by putting a colon in front of it. In managed C++, unlike regular unmanaged C++, you can use only one base class and a list of parameters, because only single inheritance is supported here.

Hotel(// Hotel
String*city,
String*name
int number, // number
Decimal cost) // Decimal cost
: Reservable(number, cost) // number, cost
{
City = city;
// City = city;
HotelName = name; // title
}

Note that in managed C++, you can only call the constructor of the base class from which the class was directly derived. You cannot call a constructor that is higher in the inheritance hierarchy.