Inheritance in C++: Visibility Modes & Protected Members
Overview: Public inheritance can express that a SavingsAccount is an Account.
What is Inheritance?
- In real life, a child inherits qualities (like eye color or height) and property from their parents.
- BASE CLASS (Parent) Vehicle speed, fuelCapacity, startEngine()
- DERIVED CLASS (Child) Car Gets all Vehicle features automatically + adds: numberOfDoors, openSunroof()
- Why is Inheritance so Important?: Code Reusability: You don’t have to rewrite the same code again and again.
- Real-World “IS-A” Modeling: Easily models relationships like:
- A Car IS-A Vehicle.
- A Student IS-A Person.
- A Manager IS-AN Employee.
View diagram · Base Class to Derived Class Inheritance
Syntax of Inheritance
- Exam Tip: If you forget to write the visibility mode (e.g.
Why Do We Need the protected Access Specifier?
- Let’s understand the problem with
privateandpublic: - If you make a variable
private, it is hidden from the outside world — but it is also completely hidden from child classes! - If you make a variable
public, your child class can access it — but now any code inmain()can also change it directly, which…
The Three Visibility Modes (Practice Question!)
- When a child class inherits a parent class, the Visibility Mode decides how the parent’s members appear inside the child class:
private: Never Inherited (Hidden)protected: Becomesprotectedpublic: Becomespublic- Easy Explanation of the 3 Modes: Public Inheritance (
class B : public A): The most common mode. - Protected Inheritance (
class B : protected A): Bothpublicandprotectedmembers of the parent becomeprotectedin the child. - Private Inheritance (
class B : private A): Bothpublicandprotectedmembers becomeprivateinside the child class.
Forms of Inheritance, The Diamond Problem & Virtual Base Classes
Overview: A diamond arises when two intermediate classes inherit the same base and one class inherits both.
The Five Forms of Inheritance in C++
- In C++, you can link classes together in 5 different ways:
- 1. Single Inheritance One child class inherits from one parent class.
- 2. Multilevel Inheritance One derived class becomes the parent of another.
- 3. Multiple Inheritance One child class inherits from two or more parent classes.
- 4. Hierarchical Inheritance One parent class is inherited by multiple child classes.
- 5. Hybrid Inheritance A mix of two or more inheritance types (e.g.
View diagram · The 5 Forms of Inheritance
Ambiguity in Multiple Inheritance
- In Multiple Inheritance, a child class inherits from two parent classes.
The Diamond Problem in Hybrid Inheritance
- The most famous inheritance problem in C++ exams is the Diamond Problem (Multipath Inheritance):
- Why is it a problem?:
Class BinheritsClass A, so it gets a copy ofrollNo. Class Calso inheritsClass A, so it gets another copy ofrollNo.- Now
Class Dinherits from bothClass BandClass C. - As a result,
Class Dgets TWO DUPLICATE COPIES ofrollNo! - When you write
objD.rollNo = 101;, the compiler throws an error: *“Ambiguous request for rollNo!
View diagram · The Diamond Problem in Multiple Inheritance
The Solution: Virtual Base Classes
- To fix this duplicate copy bug, C++ gives us Virtual Base Classes.
- “Hey C++, make sure only ONE SINGLE shared copy of Class A is passed down to all future child classes!”
Order of Constructor Execution in Inheritance
- When you create an object of a derived class:
- Virtual Base Class constructors run FIRST.
- Then, normal Base Class constructors run in order from left to right as listed in the class header.
- Finally, the Derived Class constructor runs last.
Virtual Functions, Abstract Classes & Runtime Polymorphism
Overview: A Shape reference can refer to a Circle or a Rectangle.
What is Polymorphism?
- The word Polymorphism comes from two Greek words: Poly (meaning many) and Morph (meaning forms).
- 1. Compile-Time (Early / Static Binding) The compiler decides which function to call while compiling the code.
- 2. Run-Time (Late / Dynamic Binding) The decision of which function to call is delayed until the program actually runs, based on the real object in RAM.
View diagram · The Two Branches of Polymorphism in C++
The Problem: Base Pointer to Derived Object
- In C++, a parent (base) pointer is allowed to hold the address of any child (derived) object:
- Why did this happen?: By default, C++ uses Early Binding (Compile-Time Binding).
The Solution: Virtual Functions (Late Binding)
- To fix this, we put the
virtualkeyword before the function in the base class: - *“Hey compiler!
Pure Virtual Functions & Abstract Classes
- Imagine you have a base class called
Shape. - What is an Abstract Class?: An Abstract Class is any class that contains at least one Pure Virtual Function.
- No Direct Objects You CANNOT create direct objects of an abstract class ( Shape s; will give an error!).
- Pointers are Allowed You CAN create pointers to an abstract class ( Shape *ptr; ) to achieve runtime polymorphism.
- Mandatory Overriding Every derived child class MUST override and provide code for all pure virtual functions, or it becomes abstract too!
- Acts as a Blueprint Contract Ensures that every child shape will definitely implement area() .
Operator Overloading & Type Conversion in C++: Unary & Binary
Overview: Overloading plus for a Money class can return a new sum while leaving its operands intact.
What is Operator Overloading?
- In C++, regular operators like
+,-, and*work naturally with built-in data types likeintandfloat(for example:5 + 3gives8).
Rules for Operator Overloading (Golden Exam Rules)
- Only Existing Operators: You can only overload operators that already exist in C++.
- Precedence Stays the Same: You cannot change the natural priority of operators (
*will always be calculated before+). - Cannot Change Operands Count: Unary operators (like
++) must remain unary; binary operators (like+) must remain binary. - Must Involve a Class Object: You cannot change how basic integers work (you cannot redefine
int + int). - The 5 Operators that CANNOT Be Overloaded in C++: (Examiners ask this in almost every exam!)
- 1. Dot Operator (.) Class member access operator.
- **2.
- 3. Scope Resolution (::) Scope resolution operator.
View diagram · The 5 Non-Overloadable Operators in C++
Overloading the Binary + Operator
- When overloading a binary operator (like
+): - As a Member Function: Takes only 1 argument!
- As a Friend Function: Takes 2 arguments (because friend functions have no
thispointer):
Type Conversion in C++
- Sometimes you need to convert between basic data types (like
int) and user-defined class objects. - A. Basic Type to Class Type (Using Constructor): To convert a primitive number (e.g., total minutes =
135) into aTimeobject (2 hrs 15 mins), write a **Single-Argument… - B. Class Type to Basic Type (Using Casting Operator): To convert an object back into a basic primitive type, use a Casting Operator Function:
- Rules: Must be a class member function, has no return type written, and accepts zero parameters.
Pointers with Arrays & The ‘this’ Pointer in C++
Overview: For an array, adding one to an element pointer advances to the next element of its type.
What is a Pointer?
- A Pointer is a special variable that stores the memory address of another variable.
- Address-of Operator (
&): Gives the memory address of a variable (e.g. - Dereference Operator (
*): Gets the actual value stored at that address (e.g. - Pointer Arithmetic: When you write
ptr++, the computer does not just add 1 to the address number. - For an
intpointer:ptr + 1jumps ahead by 4 bytes. - For a
doublepointer:ptr + 1jumps ahead by 8 bytes.
Pointers with Arrays
- In C++, an array name without any brackets is actually a pointer to its first element (
arr == &arr[0]).
View diagram · Pointer-Subscript Equivalence Rule
Pointers to Objects & The Arrow Operator (->)
- Just like primitive integers, you can also create pointers that point to class objects.
The this Pointer in C++
- When you have 5 objects of a class and one of them calls
obj1.display(), how does the function know which object called it? - 1. Resolving Name Conflicts Separates class variables from function parameters when both have the exact same name ( this->age = age; ).
- 2. Method Chaining Returning *this allows you to chain multiple function calls in one single line: obj.setName(“Aman”).setAge(21);
- 3. Self-Assignment Check Used in operator overloading to make sure an object isn’t being assigned to itself ( if (this != &obj) ).
View diagram · The Three Critical Roles of the ‘this’ Pointer
C++ Streams, Formatted I/O & Exception Handling
Overview: Stream formatting controls how values appear, such as showing a fee with two decimal places.
What is a Stream in C++?
- Think of a Stream like water flowing through a pipe.
- Input Stream: Bytes flowing from an input device (like keyboard or file) into the program (
cin >>). - Output Stream: Bytes flowing from your program out to a destination (like monitor screen or printer) (
cout <<). - Source Device Keyboard (standard input) or disk file
- Input Stream (cin) Flow of byte sequences into program memory
- C++ Program Computes logic and prepares results
- Output Stream (cout) Flow of formatted bytes delivered to screen
View diagram · C++ Input/Output Stream Architecture
C++ Stream Class Hierarchy
- C++ organizes all input and output classes into a neat family tree:
- ios (Root Base Class) The foundation class.
- istream (Input Stream) Inherits from ios .
- ostream (Output Stream) Inherits from ios .
- iostream (Both Input & Output) Inherits from both istream and ostream (Multiple Inheritance) for two-way reading and writing.
View diagram · C++ Stream Class Inheritance Tree
Unformatted vs. Formatted I/O Operations
- A. Unformatted I/O (Raw Character Data): Reads and writes raw characters without any special formatting or columns:
cin.get(ch):istreamcout.put(ch):ostreamcin.getline(buf, size):istreamcout.write(buf, size):ostream- B. Formatted I/O Using
<iomanip>Manipulators: Manipulators change how output is displayed (adding columns, padding characters, or setting decimal places):
Exception Handling in C++ (try, catch, throw)
- In simple programs, we use
if-elseto check errors. - 1. try Block Wrap the risky code here that might cause an error at runtime.
- 2. throw Statement When an error occurs, you throw an error message or error code out of the try block.
- 3. catch Block Catches the thrown error and displays a friendly message to the user instead of crashing!
View diagram · The Three Pillars of Exception Handling
Practical Code Example: Safe Division Calculator
- Dividing by zero in math is undefined.