π Lecture 23 β Protected Access Specifier, IS A Relationship
π Overview: This lecture addresses the problem of accessing helper functions in derived classes when they are declared private in the base class. It introduces the protected access specifier as a solution that balances encapsulation with inheritance needs, and explains the IS A relationship and how derived class objects can be used where base class objects are required.
ποΈ Topics Covered
The lecture covers accessing base class member functions in derived classes and the limitation of private members for helper functions. It introduces the protected access specifier as a solution, explaining its scope and drawbacks. The concept of the IS A relationship in public inheritance is explained with examples, along with the rules for using derived class objects in place of base class objects using pointers and references. Static typing and its role in member access are also discussed.
π Lecture Summary
Accessing base class member functions in derived class
Public methods of a base class can be directly accessed in its derived class. However, some class member functions serve as helper functions for other class members and should not be called directly using a class object. For example, a function that checks if a string contains only integers, functions for encryption/decryption, or the IsLeapYear(int) function in a Date class.
These helper functions are typically made private because there is no need to access them using a class object directly. Making them private works fine until we derive a child class that needs those functions. For instance, a SpecialDate class derived from Date to handle only working days would need the IsLeapYear function, but it cannot access it because private members are only accessible within the class they belong to.
Solution: Modify Access Specifier β One solution is to make the helper function public, but this exposes it to everyone, which defeats the purpose of encapsulation.
π Definition β Helper functions: Member functions written to assist other member functions of the class, not intended to be called directly by external code.
βprotectedβ access specifier
C++ provides the protected access specifier for situations where a function in a base class should be accessible in its derived classes but not outside of the class. The scope of protected access is between private and public β it prevents external access (like private) while allowing access in derived classes (like public).
Protected members of a class cannot be accessed outside the class but are accessible in derived classes of that class. Protected members of a base class become protected members of the derived class (in public and protected inheritance; in private inheritance they become private).
class Date {
// ...
protected:
bool IsLeapYear(int );
};
int main(){
Date aDate;
aDate.IsLeapYear(); // Error β not accessible outside the class
return 0;
}
// In derived class β accessible
void SpecialDate::AddSpecialYear(int i) {
if(day == 29 && month == 2 && !IsLeapyear(year+i)) { /* OK */ }
}
π Definition β Protected: An access specifier that makes members accessible within the class itself and in derived classes, but not outside the class hierarchy.
π‘ Why this matters: Protected members allow derived classes to reuse base class implementation details without exposing them to the entire program.
Disadvantages of protected Members: Protected members break encapsulation because they become part of both the base class's implementation and the derived class's implementation. This violates the principle that "a class data members and functions should be encapsulated in the class itself."
π Principle: Protected members compromise encapsulation by making base class implementation details accessible to derived classes.
βIS Aβ Relationship
Public inheritance models the "IS A" relationship. For example:
- Line IS A Shape
- Circle IS A Shape
- Triangle IS A Shape
The general principle is: "Derived Object IS A kind of Base Object" β meaning a derived class object is a special kind of base object with extra properties (attributes and behavior).
Derived class objects can be used where base class objects are required because the derived class object contains an implicit base class object. However, the reverse is not true β a base class object cannot be used where a derived class object is required because a base class only has the base part, not the derived class part.
π Example:
class Person {
char * name;
public:
const char * GetName();
};
class Student: public Person {
int rollNo;
public:
int GetRollNo();
};
int main() {
Student sobj;
cout << sobj.GetName(); // OK β accessible from base
cout << sobj.GetRollNo(); // OK β accessible from derived
return 0;
}
Static Type
Static type is the type used to declare a reference or pointer. For example:
- In
Person * pPtr = 0;β the static type ofpPtrisPerson* - In
Student s;β the static type ofsisStudent
Member Access is determined by the static type of the pointer or reference. A base class pointer can hold the address of a derived class object, but it can only access the interface of the base class.
int main() {
Person * pPtr = 0;
Student s;
pPtr = &s; // OK β derived to base conversion
cout << pPtr->GetName(); // OK β GetName is in Person
cout << pPtr->GetRollNo(); // Error β GetRollNo not in Person
return 0;
}
This also applies to references:
int main() {
Person p;
Student s;
Person & refp = s; // Reference to derived object
cout << refp.GetName(); // OK
cout << refp.GetRollNo(); // Error
return 0;
}
Explicit use of IS A relationship: Using a base class reference or pointer to refer to a derived class object.
Implicit use of IS A relationship: Passing a derived class object to a function that expects a base class reference or pointer.
void Play(const Person& p) {
cout << p.GetName() << " is playing";
}
void Study(const Student& s) {
cout << s.GetRollNo() << " is studying";
}
int main() {
Person p;
Student s;
Play(p); // OK β Person reference initialized with Person
Play(s); // OK β Student IS A Person, implicit conversion
return 0;
}
π Definition β Static Type: The type used to declare a pointer or reference variable, which determines at compile time which member functions can be accessed through that variable.
π Rule: A derived class object can always be used where a base class object is expected, but not vice versa.
β Key Takeaways
The protected access specifier provides a middle ground between private and public, allowing derived classes to access base class members while preventing external access, though it partially breaks encapsulation. The IS A relationship means that a derived class object is a specialized version of the base class object and can be used wherever a base class object is expected. However, static typing determines member access β a base class pointer or reference can only access base class members, even when pointing to a derived class object. The implicit and explicit use of this relationship is crucial for polymorphic function calls and interface design in object-oriented programming.
π§ Quick Revision Questions
- What is the problem with making helper functions private when you later need to create a derived class?
- How does the protected access specifier differ from both private and public?
- What is the main disadvantage of using protected members in terms of object-oriented principles?
- Can a base class pointer be used to call a derived class member function? Why or why not?
- What does static type mean, and how does it affect member access when using inheritance?
π Lecture 24 β Protected Access Specifier, IS-A Relationship, Copy Constructor and Inheritance
π Overview: This lecture explores key inheritance concepts in C++, including the protected access specifier and its role in derived classes, the IS-A relationship that governs public inheritance, and the detailed mechanics of copy constructors and assignment operators when working with base and derived classes. Understanding these topics is essential for building robust, memory-safe object-oriented programs.
ποΈ Topics Covered
The lecture covers protected member access specifiers and their significance in inheritance, the IS-A relationship that defines public inheritance, static type of identifiers and its role in member access, copy constructors in inheritance scenarios including compiler-generated default behavior, shallow vs deep copying, and assignment operators in derived classes. It also examines explicit vs implicit calls to base class member functions and assignment operators, and concludes with an appendix on type casting operations including upcasting, downcasting, static_cast, dynamic_cast, and reinterpret_cast.
π Lecture Summary
Protected Members
Protected members are between public and private - they are used in inheritance. From outside the class, no one can access protected members. However, any publicly derived class can access protected members, and they behave as protected members of the derived class. In a single standalone class, the protected access specifier has no significance, but when deriving a class, it becomes significant.
π Definition β Protected access specifier: A member access level where members are accessible to derived classes but not to outside code.
IS-A Relationship
Inheritance is used when two classes have an IS-A kind of relationship. In C++, public inheritance is used for IS-A relationships. A publicly derived class pointer can be used for its base class pointer because the derived class is a kind of base class. For example, in "Student IS-A Person" relationship, a student has all properties of a person (walks, eats, drinks) but also has extra properties like studying in a program. The compiler treats assigning a derived class pointer to a base class pointer as an explicit manifestation of the IS-A relationship.
Static Type of an Identifier
The static type of an identifier is the type used to declare it. For example, Student * student; has a static type of Student, and Person * person; has a static type of Person. Access to members of an identifier is governed by its static type - the compiler uses static type to determine which members (functions and variables) the identifier can use.
π Definition β Static type: The type used to declare an identifier, which governs member access at compile time.
Copy Constructor
A copy constructor is a member function of a class used to create an object by copying values from an already existing object.
Copy Constructor in Case of Inheritance
Consider two classes, Person (base) and Student (derived). Person has an attribute name, and Student has an attribute major. The code (Listing 24.1) demonstrates copy constructor behavior in inheritance. In main(), creating Student sobj1("Ali","Computer Science") then Student sobj2 = sobj1; invokes the compiler-generated default copy constructor for Student, which in turn calls the copy constructor of the base class Person. The base class anonymous object is created first, then the derived part is created.
π‘ Why this matters: The order of construction (base first, then derived) is critical when using copy constructors, as the derived class copy constructor must properly initialize the base class part.
Shallow Copy
The compiler by default uses shallow copy. In shallow copy, both char * name and char * major pointers of both objects (sobj1 and sobj2) point to the same memory locations. The compiler generates a copy constructor for the derived class, calls the base class copy constructor, and then performs shallow copy of the derived class's data members. The problem with shallow copy is that when one object is destroyed (freeing its dynamically allocated memory), the other object's pointers become invalid (dangling pointers).
π Definition β Shallow copy: A copy operation where only pointer values are copied, not the memory they point to, causing both objects to share the same dynamically allocated memory.
Deep Copy
Deep copy solves the shallow copy problem by writing custom copy constructor code. The solution is to allocate new dynamic memory for the copied object so it doesn't rely on the original object's memory. First, write a custom copy constructor for the base class Person:
Person::Person(const Person & rhs): name(NULL){
if (rhs.name != NULL) {
name = new char[strlen(rhs.name)+1];
strcpy(name,rhs.name);
}
}
When the derived class copy constructor is written, it must explicitly call the base class copy constructor from its initialization list. Without this explicit call, the compiler calls the base class default constructor (not the copy constructor), resulting in missing data (e.g., name being NULL). The correct derived class copy constructor is:
Student::Student(const Student & rhs) : Person(rhs), major(NULL) {
if (rhs.major != NULL) {
major = new char [strlen(rhs.major)+1];
strcpy(major,rhs.major);
}
}
π Definition β Deep copy: A copy operation that allocates new memory for dynamically allocated members and copies the actual data, not just pointers.
π Copy constructor execution order: When Student sobj2 = sobj1; is executed with user-defined deep copy constructors:
- Student copy constructor is invoked
- Person copy constructor (base class) is called from initialization list
- Deep copy of base class data members (name)
- Deep copy of derived class data members (major)
Assignment Operator
The compiler also generates an assignment operator for a class if needed. In inheritance, when assigning one derived class object to another, the derived class copy assignment operator is invoked, which in turn calls the base class assignment operator. Dynamic memory allocation requires writing a user-defined assignment operator, similar to the copy constructor. The derived class assignment operator must explicitly call the base class assignment operator.
Calling Base Class Member Functions
There are two ways to call base class functions from derived class:
Explicit Way: Mention the base class name using Person::GetName(). Even without the base class name, the call works because the derived class can access its base class public methods.
Implicit Way: Use static_cast<const Person &>(*this).GetName() - casting the derived object to a base class reference and calling the method.
Assignment Operator in Derived Classes
The assignment operator of the base class is not automatically called when a derived class has a user-defined assignment operator. To call it explicitly:
Person::operator = (rhs); // Explicit call
To call it implicitly:
static_cast<Person &>(*this) = rhs; // C++ way of type casting
Before performing the deep copy of derived class data members, the code must delete previously allocated memory for major to avoid memory leaks: if (major != NULL) delete [] major;
β Key Takeaways
Students must remember that the protected access specifier allows derived classes to access members while hiding them from external code, and public inheritance models the IS-A relationship. Copy constructors in inheritance require careful handling: if a derived class defines a custom copy constructor, it must explicitly call the base class copy constructor from its initialization list, otherwise the base class default constructor runs and data is lost. Shallow copy by the compiler creates dangling pointers when dynamic memory is involved, so deep copy must be implemented manually. Similarly, derived class assignment operators must call base class assignment operators and delete old dynamically allocated memory before performing deep copy. Casting operations like static_cast, dynamic_cast, and reinterpret_cast enable type conversions in inheritance, with upcasting (derived to base) being safer than downcasting (base to derived).
π§ Quick Revision Questions
- What happens to the name attribute of a Student object when a derived class copy constructor is defined but does not explicitly call the base class copy constructor?
- Why does the compiler generate a copy constructor for the derived class even when the base class has a user-defined copy constructor?
- In shallow copy, what problem occurs when one object's destructor is called to free dynamically allocated memory?
- What is the correct syntax to implicitly call the base class assignment operator from a derived class assignment operator?
- Explain the difference between upcasting and downcasting, and name one casting operator suitable for each.
π Lecture 25 β Overriding Member Functions of Base Class in Derived Class (Function Overriding)
π Overview: This lecture explains how a derived class can override (redefine) member functions of its base class by providing a function with the same signature. It distinguishes function overriding from overloading, demonstrates practical examples including calling base class versions from derived class methods, and introduces the hierarchy of inheritance with direct and indirect base classes.
ποΈ Topics Covered
The lecture covers function overriding vs. function overloading, overriding member functions of base class (with examples of totally changing or extending function behavior), how to properly call a base class overridden method using scope resolution, the problem of recursive calls, and pointer behavior with overridden functions. It also introduces hierarchy of inheritance, direct base classes, and indirect base classes.
π Lecture Summary
Overloading vs. Overriding
Function Overloading occurs within the scope of one class β two functions with the same name but different parameters and return type. Function Overriding occurs across parent and child classes in an inheritance hierarchy β the derived class provides a function with the same signature (same name, parameters, and return type) as the base class function. Overriding within the scope of a single class causes a compilation error due to duplicate declaration.
π Definition β Function Overriding: The derived class redefines a base class member function with the same signature to change or extend the behavior.
π Example: class Parent { public: void Func1(); void Func1(int); }; shows overloading; class Child : public Parent { public: void Func1(); }; shows overriding.
Overriding Member Functions of Base Class
A derive class can override a base class member function so that the working of the function is totally changed. Example: class ParalyzedPerson : public Person { public: void Walk(); };
A derive class can also override a base class member function so that the working is similar to the former implementation but extended. Example: class Student : public Person overrides Print() to display both name (from Person) and major.
class Student : public Person {
char * major;
public:
Student(char * aName, char* aMajor);
void Print(){
cout << "Name: " << GetName() << endl
<< "Major: " << major << endl;
}
};
Output: Name: Ahmed then Major: Computer Science
Calling Base Class Overridden Function from Derived Class
A derived class can call the base class member function from its overridden function to perform the base class part first, then add its own tasks. This aligns with OOP principles where each class handles its own responsibilities.
The wrong way causes infinite recursion:
void Print(){
Print(); // Calls itself recursively β infinite loop
cout << "Major:" << major << endl;
}
To fix this, use the scope resolution operator :::
void Print(){
Person::Print(); // Correctly calls base class Print
cout << "Major:" << major << endl;
}
Output: Name: Ahmed then Major: Computer Science
π‘ Why this matters: Without scope resolution, the compiler calls the derived class version, causing infinite recursion. Scope resolution explicitly tells the compiler to call the base class version.
Pointer Behavior with Overridden Methods
When using pointers to call overridden methods, they are called according to the static type of the pointer, not the actual object type.
int main(){
Student a("Ahmad", "Computer Science");
Student *sPtr = &a;
sPtr->Print(); // Calls Student::Print() because sPtr is Student*
Person *pPtr = sPtr; // Static type is Person*
pPtr->Print(); // Calls Person::Print() because pPtr is Person*
return 0;
}
Output:
Name: Ahmed
Major: Computer Science
Name: Ahmed
This behavior is often undesirable β calling the base class version when you want the derived version. The lecture notes that this problem will be solved using virtual functions in a later lecture.
Hierarchy of Inheritance
Inheritance relationships are represented in a tree-like hierarchy. The root is the most base class, and branches represent derived classes.
π Definition β Direct Base Class: A base class explicitly listed in a derived class's header with a colon (:). Example: class Child1 : public Parent1 { ... }; Here, Parent1 is a direct base class of Child1.
π Definition β Indirect Base Class: A base class not explicitly listed in a derived class's header with a colon, but inherited from two or more levels up the hierarchy. Example:
class GrandParent { ... };
class Parent1 : public GrandParent { ... };
class Child1 : public Parent1 { ... }; // GrandParent is an indirect base class of Child1
β Key Takeaways
Function overriding allows a derived class to redefine a base class member function with an identical signature (name, parameters, return type), whereas function overloading occurs within the same class with different parameters. When overriding, always use scope resolution (Base::Method()) to call the base class version from the derived version to avoid infinite recursion. Pointers call overridden functions based on their static type, not the actual object type β this limitation is later resolved by virtual functions. Finally, inheritance is organized as a hierarchy with direct base classes (explicitly listed) and indirect base classes (inherited from higher levels).
π§ Quick Revision Questions
- What is the key difference between function overloading and function overriding in C++?
- Why does calling
Print()(without scope resolution) inside the Student'sPrint()method cause infinite recursion? - How do you correctly call the base class version of an overridden function from the derived class?
- Given a
Person*pointer pointing to aStudentobject, which version ofPrint()is called? Why? - What is the difference between a direct base class and an indirect base class? Give an example of each.
π Lecture 26 β Base Initialization
π Overview: This lecture explores the concept of base initialization in class hierarchies, focusing on which constructors a derived class can call during initialization. It also introduces the three types of inheritance in C++, with detailed coverage of private and protected inheritance, including practical examples of when each type is appropriate.
ποΈ Topics Covered
The lecture covers base initialization rules in class hierarchies, including the restriction that a child can only call its direct base class constructor. It then explains function overriding in hierarchy and presents the three types of inheritance: public, protected, and private. Detailed examples are provided for private inheritance, demonstrating how to model "implemented in terms of" relationships using the Set and Collection classes.
π Lecture Summary
26.1. Base Initialization
In class hierarchies, the child class can only call the constructor of its direct base class to perform initialization using its constructor initialization list. The child cannot call the constructor of any of its indirect base classes for initialization.
π Definition β Direct Base Class: The immediate parent class from which a derived class directly inherits. π Definition β Indirect Base Class: A class that is higher in the hierarchy but not the immediate parent (e.g., grandparent).
π Example:
class GrandParent {
int gpData;
public:
GrandParent() : gpData(0) {...}
GrandParent(int i) : gpData(i) {...}
void Print() const;
};
class Parent1: public GrandParent {
int pData;
public:
Parent1() : GrandParent(), pData(0) {...}
};
class Child1 : public Parent1 {
public:
Child1() : Parent1() {...}
Child1(int i) : GrandParent(i) //Error: indirect base class
{...}
void Print() const;
};
In the above, Child1 constructor cannot call GrandParent's constructor from its initialization list because GrandParent is an indirect base class.
Overriding in class hierarchy means that a child class can override (redefine) the function of any of its parent classes, whether direct or indirect.
π Example of overriding:
void GrandParent::Print() {
cout << "GrandParent::Print" << endl;
}
void Child1::Print() {
cout << "Child1::Print" << endl;
}
int main(){
Child1 obj;
obj.Print(); // Calls Child1::Print
obj.Parent1::Print(); // Calls GrandParent::Print (no override in Parent1)
obj.GrandParent::Print(); // Calls GrandParent::Print directly
return 0;
}
Output:
Child1::Print
GrandParent::Print
GrandParent::Print
π‘ Why this matters: Understanding which constructors can be called is essential for proper object initialization in deep hierarchies. The function overriding mechanism allows polymorphic behavior while preserving access to parent versions through scope resolution.
26.2. Types of Inheritance
There are three types of inheritance specified using keywords: public, protected, and private.
a. Public Inheritance
class Child: public Parent {...};
| Member access in Base Class | Derived Class |
|---|---|
| Public | Public |
| Protected | Protected |
| Private | Hidden |
b. Protected Inheritance
class Child: protected Parent {...};
| Member access in Base Class | Derived Class |
|---|---|
| Public | Protected |
| Protected | Protected |
| Private | Hidden |
c. Private Inheritance
class Child: private Parent {...};
| Member access in Base Class | Derived Class |
|---|---|
| Public | Private |
| Protected | Private |
| Private | Hidden |
If the user does not specify the type of inheritance, the default type is private inheritance:
class Child: Parent {...}; // Equivalent to: class Child: private Parent {...};
26.3. Private Inheritance
Private inheritance is used when we want to reuse the code of some class. It models an "Implemented in terms of" relationship.
π Definition β "Implemented in terms of": A design relationship where a class uses the implementation of another class but does not expose that class's interface to the outside world.
π Example: Collection and Set classes
Consider a class Collection that stores elements:
class Collection {
...
public:
void AddElement(int);
bool SearchElement(int);
bool SearchElementAgain(int);
bool DeleteElement(int);
};
This Collection class supports:
- AddElement: to add elements to the collection
- SearchElement: searches for any element; returns true as soon as found
- SearchElementAgain: finds the second instance of an element; returns true on duplicate
- DeleteElement: deletes any entry from the collection
The Collection class allows duplicate elements. Now suppose we want to implement a Set class, which has similar functionality but cannot allow duplicate elements. We can use inheritance but not public inheritance because that would expose all Collection functions through the Set interface. We only want to use some Collection functions internally to implement Set functionality.
Using private inheritance achieves two main advantages:
- Specialization of the class according to Set requirements (removing duplicate elements)
- Making the Collection class interface inaccessible from outside world using a Set class reference
π Class Set implementation:
class Set: private Collection {
private:
...
public:
void AddMember(int);
bool IsMember(int);
bool DeleteMember(int);
};
void Set::AddMember(int i){
if (!IsMember(i))
AddElement(i); // Only adds if not already a member
}
bool Set::IsMember(int i){
return SearchElement(i);
}
π‘ Why this matters: Private inheritance allows you to leverage existing code while completely hiding the base class interface. This is crucial when you want to inherit implementation without inheriting interface β a common scenario in code reuse.
β Key Takeaways
A derived class can only call its direct base class constructor from its initialization list, not any indirect base class constructors. The three types of inheritance β public, protected, and private β control how base class members are accessible in the derived class and beyond. Public inheritance models an "is-a" relationship, while private inheritance models an "implemented in terms of" relationship suitable for code reuse without interface exposure. If no inheritance type is specified, C++ defaults to private inheritance. The default type is private inheritance, which is essential to remember for exam questions involving unspecified inheritance.
π§ Quick Revision Questions
- Why is calling
GrandParent(i)inChild1's initialization list an error in C++? - What are the three types of inheritance in C++ and what keywords specify them?
- What is the default type of inheritance if none is specified?
- In private inheritance, what access level do public members of the base class get in the derived class?
- Why would you use private inheritance instead of public inheritance for implementing a Set class from a Collection class?
π Lecture 27 β Private Inheritance and Protected Inheritance
π Overview: This lecture continues the discussion of private inheritance, emphasizing its role in implementing specialization (restriction) through the βimplemented in terms ofβ relationship. It then introduces protected inheritance, comparing its properties to private and public inheritance, and explains how each type controls the accessibility of base class members in derived classes and the outside world.
ποΈ Topics Covered
The lecture begins with a detailed review of private inheritance using the Collection and Set example. It then formally defines specialization (restriction) and explains how private inheritance explicitly implements it. The essential properties of private inheritance are listed, including conversion rules, constructor calling, and restrictions for classes more than one level down the hierarchy. Finally, protected inheritance is introduced and its properties are compared to private and public inheritance through a table and a code example.
π Lecture Summary
27.1. Specialization (Restriction)
In specialization, the derived class is behaviourally incompatible with the base class. Behaviourally incompatible means that the base class cannot always be replaced by the derived class. Specialization is represented by the βImplemented in terms ofβ relationship and can be implemented using both private and protected inheritance.
π Definition β Specialization (Restriction): A relationship where the derived class restricts or modifies the behavior of the base class, making it behaviourally incompatible. The base class cannot always be substituted by the derived class.
π Example: The Person class has an age attribute with a range of [0..125] and a setAge() function that accepts any age in that range. The Adult class specializes Person by restricting the age range to [18..125]. If someone tries to set an age below 18 in Adult, it generates an error. This shows restriction because the Adult class cannot be used everywhere the Person class is expected (it is behaviourally incompatible).
Essential Properties of Private Inheritance
- In Private Inheritance, only member functions and friend classes or functions of a derived class can convert a pointer or reference of the derived object to that of the parent object.
π Example:
void DoSomething(const Parent &);
Child::Child(){
Parent & pPtr = static_cast<Parent &>(*this); // fine
DoSomething(pPtr);
// DoSomething(*this); // this single line is equal to two lines above.
}
- As in public inheritance, the child class object has an anonymous object of the parent class.
- As in public inheritance, the default constructor and copy constructor of the parent class are called when constructing an object of the derived class.
π Example:
class Parent{
public:
Parent(){ cout << βParent Constructorβ; }
Parent(const Parent & prhs){ cout << βParent Copy Constructorβ; }
};
class Child: private Parent{
public:
Child(){ cout << βChild Constructorβ; }
Child(const Child & crhs) : Parent(crhs){ cout << βChild Copy Constructorβ; }
};
int main() {
Child cobj1; // default constructor will be invoked
Child cobj2 = cobj1; // copy constructor will be invoked
return 0;
}
Output:
Parent Constructor
Child Constructor
Parent Copy Constructor
Child Copy Constructor
- In private inheritance, the derived class that is more than one level down the hierarchy cannot access the member functions of the grandparent class. This is because
publicandprotectedmembers of the derived class become private members of the privately derived class for all practical purposes.
π Example:
class GrandParent{
public:
void DoSomething();
};
class Parent: private GrandParent{
void SomeFunction(){ DoSomething(); } // OK
};
class Child: private Parent{
public:
Child() { DoSomething(); } // Error
};
- In private inheritance, the derived class that is more than one level down the hierarchy cannot convert its pointer or reference to that of the GrandParent. The reason is that private inheritance implements specialization, and all features of the base class are restricted only to the privately derived class and its friends.
π Example:
void DoSomething(GrandParent&);
class GrandParent{};
class Parent: private GrandParent{
public:
Parent() {DoSomething(*this);} // fine
};
class Child: private Parent {
public:
Child() { DoSomething(*this); } // Error
};
π‘ Why this matters: These restrictions ensure that the specialized behavior of a privately derived class is not accidentally used in contexts where the base class is expected, maintaining the integrity of the specialization.
27.2. Protected Inheritance
If a class D has been derived using protected inheritance from class B (if B is a protected base and D is derived class), then public and protected members of B can be accessed by member functions and friends of class D and classes derived from D. Protected inheritance is used to build class hierarchy using the βImplemented in terms ofβ relationship.
class GrandParent{
public:
void DoSomething();
};
class Parent: protected GrandParent{
void SomeFunction(){ DoSomething(); } // OK
};
class Child: protected Parent{
public:
Child() { DoSomething(); } // OK (unlike private inheritance)
};
π‘ Why this matters: Protected inheritance lies between public and private inheritance. It allows the derived class and its children to access the base class features, but the outside world cannot. This is useful when you want to extend a hierarchy without exposing the base class interface to external users.
27.3. Properties of Protected Inheritance
If B is a protected base and D is derived class, then only friends and members of D and friends and members of classes derived from D can convert D* to B* or D& to B&. (In private inheritance, only the derived class or its friends can convert pointer to base class.)
π Example:
void DoSomething(GrandParent&);
class GrandParent{};
class Parent: protected GrandParent{};
class Child: protected Parent {
public:
Child() { DoSomething(*this); } // fine
};
Comparison of Public, Protected, and Private Inheritance
| Accessibility of Base Class Public Members | Public Inheritance | Protected Inheritance | Private Inheritance |
|---|---|---|---|
| In Derived 1 | Yes | Yes | Yes |
| In Derived 2, Derived 3, ... (further down hierarchy) | Yes | Yes | No |
| In Main (outside world) | Yes | No | No |
- Private data members will NOT be accessible in any derived class or in the main function.
- Protected data members will become private data members in the case of private inheritance and protected data members of the derived class in the case of protected inheritance.
A Good Programming Exercise
A good programming exercise would be to write a program that shows the accessibility of all types of member functions for all types of inheritance in derived classes.
β Key Takeaways
- Specialization (Restriction) is βimplemented in terms ofβ and is used when the derived class is behaviourally incompatible with the base class. It can be implemented using both private and protected inheritance.
- In private inheritance, only the derived class (and its friends) can access base class members and convert pointers/references to the base class. Classes further down the hierarchy cannot access grandparent members or convert to grandparent references.
- Protected inheritance allows the derived class and its descendants to access the base classβs public and protected members, but the outside world cannot. It sits between public and private inheritance.
- The choice of inheritance type controls how much of the base class interface is exposed: public allows outside access, protected allows descendants access, private restricts access to only the immediate derived class.
- In all inheritance types, the base class default and copy constructors are called when constructing derived objects, and an anonymous base class sub-object exists within the derived object.
π§ Quick Revision Questions
- What is the difference between public inheritance and private inheritance in terms of accessibility of base class public members in the main function?
- In the specialization (restriction) example of
PersonandAdult, why canβtAdultreplacePersoneverywhere? - In private inheritance, what happens when a class tries to access a grandparentβs member function from a class two levels down?
- In protected inheritance, who can convert a derived class pointer to a base class pointer?
- What are the three types of inheritance, and which one(s) implement the βimplemented in terms ofβ relationship?