Difference between Containership and Inheritance in C++
Containership: When an object of one class is created into another class then that object will be a member of that class, this type of relationship between the classes is known as containership or has_a relationship as one class contains the object of another class.
The class which contains the object and members of another class in this kind of relationship is called a container class and the object that is part of another object is called a contained object whereas the object that contains another object as its part or attribute is called a container object.
Syntax for Containership:
Below is the program to explain the concept of containership in C++:
Hello from first class
Explanation: In the second class above, there is an object of class first. This type of inheritance is known as has_a relationship as the class second has an object of class first as its member. From object f, the function of class first is called.
Inheritance: It is the capability of a class to derive properties and characteristics from another class which is known as Base Class. It is one of the most important features of Object-Oriented Programming. The class that inherits properties from another class is called Subclass or Derived Class. The class whose properties are inherited by sub-class is called Base Class or Super Class.
Explanation: The subclass_name is the name of the subclass, access_mode is the mode in which one wants to inherit this subclass. For Example, public, private, etc. The base_class_name is the name of the base class from which one wants to inherit the subclass.
Note: A derived class doesn’t inherit access to private data members. However, it does inherit a full parent object, which contains any private members which that class declares.
Below is the program to explain Inheritance in C++:
Child ID is 7 Parent ID is 91
Explanation: In the above program, the child class is publicly inherited from the parent class so the public data members of the parent class will also be inherited by the child class.
Difference between Inheritance and Containership:
|It enables a class to inherit data and functions from a base class||It enables a class to contain objects of different classes as its data member.|
|The derived class may override the functionality of the base class.||The container class can’t override the functionality of the contained class.|
|The derived class may add data or functions to the base class.||The container class can’t add anything to the contained class.|
|Inheritance represents a “is-a” relationship.||Containership represents a “has-a” relationship.|