AIOU LIBRARY • READ ONLY
AIOULIBRARY.COM • CODE 3401
AIOU LIBRARY • DO NOT COPY
Unit 5: Advanced Object-Oriented Programming and File Handling in C++
Easy Chapter Introduction & Learning Objectives
Welcome to Unit 5 of Course 3401, Programming Fundamentals! In earlier units, you learned how to create basic classes, objects, and functions in C++. You understand how to bundle data and functions together into a single unit. Now, we are ready to step into the world of Advanced Object-Oriented Programming (OOP) and File Handling. These concepts are the secret tools that professional software engineers use to write clean, reusable, and secure programs that can save permanent data on a computer hard drive.
Imagine you are building a student management system for Allama Iqbal Open University (AIOU). You have a general class called Student with attributes like name and roll number. But what about tutor students, regular students, or international students? Instead of writing brand-new code from scratch for every single type, OOP lets us pass traits from a parent class to a child class. This is called Inheritance. Furthermore, what if your program crashes because a user types a letter instead of a number? We will learn how to catch those errors safely using Exception Handling. Finally, we will learn how to save student grades permanently into text files so they do not disappear when the computer turns off using File Handling.
By the end of this comprehensive study guide, you will be able to:
- Understand and apply the concept of Inheritance and its various types (Single, Multiple, Multilevel, Hierarchical, and Hybrid) in C++.
- Master Function Overriding and Virtual Functions to achieve dynamic run-time behavior.
- Differentiate between compile-time and run-time Polymorphism and create Abstract Classes with pure virtual functions.
- Customize standard C++ operators (like
+or-) to work seamlessly with your own user-defined classes through Operator Overloading. - Write robust error-free code using try, catch, and throw blocks for Exception Handling.
- Perform read and write operations on external text and binary files using C++ Stream I/O Operations.
Detailed Explanation of Every Unit Topic (With Simple Examples)
1. Inheritance and Types of Inheritance
What is Inheritance? Inheritance is one of the most powerful pillars of Object-Oriented Programming. In real life, children inherit physical traits, habits, and properties from their parents. Similarly, in C++, inheritance allows a new class (called the Derived Class or Child Class) to take over the properties, variables, and member functions of an existing class (called the Base Class or Parent Class).
Why do we use Inheritance? The primary goal of inheritance is Code Reusability. If you write code once in a parent class, you do not need to rewrite it in every child class. This saves time, reduces bugs, and makes large programs easier to maintain.
Let us look at the common types of inheritance in C++:
- Single Inheritance: A single child class inherits from a single parent class. Real-Life Example: A class
Carinherits from a base classVehicle. - Multilevel Inheritance: A derived class inherits from another derived class, forming a chain or generational hierarchy. Real-Life Example: Class
LivingBeing-> derived classHuman-> further derived classEmployee. - Multiple Inheritance: A single child class inherits properties from two or more parent classes simultaneously. Real-Life Example: A class
TeachingAssistantinherits from both classStudentand classTeacher. - Hierarchical Inheritance: Multiple child classes inherit from a single common parent class. Real-Life Example: Parent class
Accounthas multiple child classes likeSavingsAccount,CurrentAccount, andLoanAccount. - Hybrid Inheritance: A combination of two or more types of inheritance (e.g., a mix of Multilevel and Multiple inheritance).
Simple C++ Code Example of Single Inheritance:
#include <iostream>
using namespace std;
// Base Class
class Person {
public:
string name;
int age;
void displayPerson() {
cout << "Name: " << name << ", Age: " << age << endl;
}
};
// Derived Class inheriting from Person
class Student : public Person {
public:
int studentID;
void displayStudent() {
cout << "Student ID: " << studentID << endl;
}
};
int main() {
Student s1;
s1.name = "Ali Ahmed";
s1.age = 21;
s1.studentID = 3401;
s1.displayPerson(); // Inherited method
s1.displayStudent(); // Own method
return 0;
}
2. Function Overriding and Virtual Functions
Function Overriding: When a child class defines a function with the exact same name, return type, and parameters as a function already declared in its parent class, it is called function overriding. The child class version "overrides" or replaces the parent class version when called on an object of the child class.
Virtual Functions: Sometimes, we work with pointers to base classes that point to objects of derived classes. By default, C++ decides which function to run at compile-time based on the pointer type. If we want C++ to decide at run-time (depending on the actual object being pointed to), we use the keyword virtual before the parent class function declaration. This is the cornerstone of dynamic polymorphism.
Simple C++ Code Example:
#include <iostream>
using namespace std;
class AIOUCourse {
public:
// Virtual function
virtual void printInfo() {
cout << "This is a general AIOU course." << endl;
}
};
class ProgrammingCourse : public AIOUCourse {
public:
// Overriding the base class function
void printInfo() override {
cout << "This is Course 3401: Programming Fundamentals (C++/Python)." << endl;
}
};
int main() {
AIOUCourse *ptr;
ProgrammingCourse progObj;
ptr = &progObj;
// Because printInfo is virtual, it calls ProgrammingCourse's version at run-time!
ptr->printInfo();
return 0;
}
3. Polymorphism and Abstract Classes
Polymorphism: The word "Polymorphism" comes from Greek meaning "many forms." In programming, it means the ability of a single function name, operator, or pointer to behave in different ways depending on the object or data type it is acting upon. Polymorphism is divided into two types:
- Compile-time Polymorphism (Early Binding): Achieved via Function Overloading and Operator Overloading.
- Run-time Polymorphism (Late Binding): Achieved via Virtual Functions and Function Overriding.
Abstract Classes: An abstract class is a special class designed only to act as a parent (base) class. It cannot be instantiated directly (meaning you cannot create an object of an abstract class). A class becomes abstract if it contains at least one Pure Virtual Function (a virtual function set to equal zero, like virtual void draw() = 0;). Any child class that inherits from an abstract class *must* override and implement that pure virtual function, otherwise the child class will also remain abstract.
Simple C++ Code Example of an Abstract Class:
#include <iostream>
using namespace std;
// Abstract Base Class
class Shape {
public:
// Pure Virtual Function
virtual void calculateArea() = 0;
};
class Square : public Shape {
private:
float side;
public:
Square(float s) { side = s; }
void calculateArea() override {
cout << "Area of Square: " << (side * side) << endl;
}
};
int main() {
// Shape s; -> ERROR! Cannot instantiate abstract class.
Square sq(5.0);
sq.calculateArea(); // Outputs: Area of Square: 25
return 0;
}
4. Operator Overloading
C++ provides built-in operators like +, -, *, ==, and << that work natively with primitive data types like int and float. However, primitive operators do not know how to add two custom user-defined objects (for example, adding two Complex Numbers or two Distance objects). Operator Overloading allows us to redefine the behavior of these operators so they can work with our custom classes.
To overload an operator, we use the keyword operator followed by the symbol we want to overload (e.g., operator+).
Simple C++ Code Example (Overloading the + operator):
#include <iostream>
using namespace std;
class Distance {
public:
int meters;
Distance(int m) {
meters = m;
}
// Overloading the '+' operator
Distance operator + (Distance d) {
Distance temp(0);
temp.meters = meters + d.meters;
return temp;
}
};
int main() {
Distance dist1(150);
Distance dist2(250);
// Adding two objects using overloaded '+' operator
Distance total = dist1 + dist2;
cout << "Total Distance: " << total.meters << " meters" << endl;
return 0;
}
5. Exception Handling in C++
Errors in programs can happen anytime. Some errors are caught at compile-time, but others happen while the program is running (run-time errors). For example, a user attempting to divide a number by zero, or trying to access an array index that does not exist. If these errors are left unhandled, the operating system forcefully crashes or terminates the program.
Exception Handling provides a structured and elegant way to catch and manage run-time errors without crashing the entire software. C++ uses three primary keywords for exception handling:
- try: The
tryblock wraps around the normal lines of code that might potentially throw an error or exception. - throw: When a problem or error condition is detected inside the try block, the program uses the
throwstatement to signal or pass an exception message. - catch: The
catchblock immediately catches the thrown exception and handles it gracefully by displaying a warning message or taking corrective action.
Simple C++ Code Example:
#include <iostream>
using namespace std;
int main() {
int num1 = 10, num2 = 0;
double result;
try {
if (num2 == 0) {
throw "Error: Division by zero is strictly prohibited!";
}
result = (double)num1 / num2;
cout << "Result: " << result << endl;
}
catch (const char* errorMessage) {
cout << "Exception caught! " << errorMessage << endl;
}
cout << "Program continues safely after exception handling." << endl;
return 0;
}
6. File Handling and Stream I/O Operations
Until now, all variables and data we stored in our programs were temporary. They lived inside the computer's volatile RAM and vanished the moment the program closed or the computer restarted. To save data permanently for future use, we must use File Handling.
In C++, file handling is performed using input/output streams provided by the <fstream> header file. There are three primary classes used for file operations:
- ofstream (Output File Stream): Used to create files and write data *to* a file from the program.
- ifstream (Input File Stream): Used to read data *from* a file into the program.
- fstream (File Stream): A general-purpose stream that can handle both reading and writing operations simultaneously.
Steps in File Handling:
- Include the
<fstream>library. - Open the file using the
open()function or constructor (linking it to a file stream object). - Perform read or write operations using insertion (
<<) and extraction (>>) operators, or line-by-line functions likegetline(). - Always close the file using the
close()function when finished to prevent data corruption and memory leaks.
Simple C++ Code Example (Writing to and Reading from a Text File):
#include <iostream>
#include <fstream>
using namespace std;
int main() {
// 1. Writing Data to a File
ofstream outFile("aiou_student_record.txt");
if (outFile.is_open()) {
outFile << "Course: Programming Fundamentals (3401)" << endl;
outFile << "Student Name: Muhammad Tariq" << endl;
outFile << "Semester: Spring 2026" << endl;
outFile.close();
cout << "Data successfully written to file!" << endl;
} else {
cout << "Error opening file for writing." << endl;
}
// 2. Reading Data from the File
string line;
ifstream inFile("aiou_student_record.txt");
if (inFile.is_open()) {
cout << "\n--- Reading from File ---" << endl;
while (getline(inFile, line)) {
cout << line << endl;
}
inFile.close();
} else {
cout << "Error opening file for reading." << endl;
}
return 0;
}
Key Terms & Easy Glossary
- Inheritance: An object-oriented mechanism that allows a child class to automatically acquire properties, attributes, and methods of a parent class. This promotes code reuse and logical hierarchy in software design.
- Base Class: Also known as the parent class or superclass, it is the original class whose properties and member functions are shared with or inherited by other child classes.
- Derived Class: Also known as the child class or subclass, it is a newly created class that inherits attributes and functions from one or more base classes, while often adding its own unique features.
- Function Overriding: A feature in object-oriented programming where a derived class provides its own specific implementation of a member function that has already been declared in its base class with the identical signature.
- Virtual Function: A special member function declared within a base class using the
virtualkeyword, telling the C++ compiler to perform dynamic binding and select the appropriate derived-class version at run-time. - Polymorphism: The capability of a single function, operator, or object reference to behave in multiple forms depending on the context or data type it interacts with. It simplifies complex coding architectures.
- Abstract Class: A base class that cannot be instantiated directly into objects because it contains at least one pure virtual function. It acts as a standardized template or blueprint for subsequent child classes.
- Operator Overloading: A compile-time polymorphism technique that lets programmers redefine standard C++ operators (such as
+,-, or*) to operate correctly on user-defined custom classes. - Exception Handling: A reliable runtime error-management mechanism in C++ utilizing
try,throw, andcatchblocks to capture unexpected errors and prevent abrupt program crashes. - File Stream I/O: A collection of C++ classes (
ofstream,ifstream,fstream) supplied in the<fstream>library that allow software programs to interact with secondary storage to permanently write, read, and manipulate files.
Q: What is inheritance and how does public inheritance differ from private inheritance in C++?
Easy Answer:
Inheritance is a fundamental Object-Oriented Programming (OOP) mechanism that allows a new class (derived class) to adopt the properties, data members, and member functions of an existing class (base class). It promotes code reusability, establishes a hierarchical relationship between classes, and reduces code redundancy.
The core differences between public and private inheritance lie in how the base class members are accessed within the derived class and by outside code (such as the main() function):
- Public Inheritance:
- Access Rule: Public members of the base class remain public in the derived class, and protected members remain protected. Private members of the base class remain strictly inaccessible to the derived class.
- Relationship: It represents an "IS-A" relationship (e.g., a
DogIS-AAnimal). - External Visibility: Objects of the derived class can directly access the public members of the base class.
- Private Inheritance:
- Access Rule: Public and protected members of the base class both become private members of the derived class. Private members remain inaccessible.
- Relationship: It represents a "Has-A" or implementation-specific relationship (sometimes called implementation inheritance).
- External Visibility: External code using the derived class object cannot access any members inherited from the base class, because they are hidden behind private access modifiers inside the derived class.
Code Example:
#iostream
using namespace std;
class Base {
public:
int x;
};
// Public Inheritance
class DerivedPublic : public Base {
// x is public here
};
// Private Inheritance
class DerivedPrivate : private Base {
// x is private here
};
int main() {
DerivedPublic obj1;
obj1.x = 10; // Valid! x is public
DerivedPrivate obj2;
// obj2.x = 10; // Error! x is private in DerivedPrivate
return 0;
}
Q: Explain the concept of virtual functions and why they are necessary for runtime polymorphism.
Easy Answer:
A virtual function is a member function declared within a base class using the virtual keyword and re-defined (overridden) in a derived class. Its primary purpose is to achieve runtime polymorphism (also known as dynamic binding).
Without virtual functions, C++ uses static binding (early binding), meaning the compiler decides which function to execute based strictly on the pointer or reference type at compile time. Virtual functions instruct the compiler to defer this decision until program execution time (late binding), checking the actual type of the object pointed to rather than the type of the pointer.
Why they are necessary:
- Dynamic Method Dispatch: When working with base class pointers or references that point to derived class objects, virtual functions ensure that the correct overridden version of the function is invoked automatically at runtime.
- Extensibility: They allow developers to write generic code that can process objects of various derived classes uniformly without needing to know their specific types beforehand.
Code Example:
#iostream
using namespace std;
class Animal {
public:
virtual void sound() { cout << "Animal makes a sound\n"; }
};
class Dog : public Animal {
public:
void sound() override { cout << "Dog barks\n"; }
};
int main() {
Animal* ptr;
Dog myDog;
ptr = &myDog;
// Calls Dog's sound() due to virtual keyword and runtime polymorphism
ptr->sound();
return 0;
}
Q: Write a C++ program to demonstrate operator overloading for the '+' operator using a complex number class.
Easy Answer:
Operator overloading allows programmers to redefine the standard behavior of operators (like +, -, *) when applied to user-defined objects. For a complex number containing a real and an imaginary part, overloading the + operator allows us to add two complex objects using natural mathematical syntax (e.g., c3 = c1 + c2).
C++ Implementation:
#iostream
using namespace std;
class Complex {
private:
float real;
float imag;
public:
// Constructor
Complex(float r = 0, float i = 0) {
real = r;
imag = i;
}
// Overloading '+' operator using a member function
Complex operator + (const Complex& obj) {
Complex temp;
temp.real = real + obj.real;
temp.imag = imag + obj.imag;
return temp;
}
// Display function
void display() {
cout << real << " + " << imag << "i" << endl;
}
};
int main() {
Complex c1(3.4, 2.5);
Complex c2(1.6, 1.5);
// Addition of two complex numbers using overloaded '+'
Complex c3 = c1 + c2;
cout << "Result of c1 + c2: ";
c3.display();
return 0;
}
Q: What is an abstract class? How does it differ from a regular concrete class?
Easy Answer:
An abstract class is a class designed specifically to act as a reliable base class from which other classes can inherit. It contains at least one pure virtual function (a virtual function set to zero, e.g., virtual void draw() = 0;). Because it is incomplete by design, you cannot instantiate objects of an abstract class directly.
Differences between an Abstract Class and a Regular Concrete Class:
- Instantiation:
- Abstract Class: Cannot be instantiated. Attempting to create an object like
Shape s;results in a compilation error. - Concrete Class: Fully implemented and can be instantiated freely (e.g.,
Circle c;).
- Abstract Class: Cannot be instantiated. Attempting to create an object like
- Virtual Functions:
- Abstract Class: Must contain at least one pure virtual function, forcing derived classes to provide their own implementation.
- Concrete Class: Contains no pure virtual functions; all inherited virtual functions are fully defined.
- Purpose:
- Abstract Class: Serves as a blueprint, template, or contractual interface for a family of derived classes.
- Concrete Class: Provides operational, ready-to-use business logic and fully functional objects.
Code Example:
#iostream
using namespace std;
// Abstract Class
class Shape {
public:
virtual void draw() = 0; // Pure virtual function
};
// Concrete Class
class Circle : public Shape {
public:
void draw() override {
cout << "Drawing a Circle\n";
}
};
int main() {
// Shape s; // Error: Cannot instantiate abstract class
Shape* sh = new Circle(); // Valid: Base pointer to derived object
sh->draw();
delete sh;
return 0;
}
Q: Describe the mechanism of try, catch, and throw blocks in C++ exception handling.
Easy Answer:
Exception handling in C++ provides a structured, robust way to detect and manage runtime errors (such as division by zero, file not found, or memory allocation failure) without crashing the application. It relies on three primary keywords: try, throw, and catch.
tryBlock: Encloses the normal statement block where a runtime error or exception might potentially occur. The program monitors this block for any signals of failure.throwStatement: When an abnormal condition or error is detected inside thetryblock, the program usesthrowto generate an exception object (which can be an integer, string, or custom class object) and halts normal sequential execution.catchBlock: Immediately follows thetryblock. It intercepts the thrown exception object, matches its data type, and executes corrective actions or error recovery code.
Code Example:
#iostream
using namespace std;
int main() {
int numerator = 10, denominator = 0, result;
try {
if (denominator == 0) {
throw "Division by zero error!"; // Throws string exception
}
result = numerator / denominator;
cout << "Result: " << result << endl;
}
catch (const char* msg) {
// Catches and handles the exception
cout << "Exception Caught: " << msg << endl;
}
cout << "Program continues safely after exception handling.\n";
return 0;
}
Q: Explain the difference between ifstream, ofstream, and fstream classes for file handling.
Easy Answer:
In C++, file handling is performed using standard library streams defined in the <fstream> header. These classes manage reading from and writing to external files safely and efficiently.
- 1.
ofstream(Output File Stream):- Purpose: Used exclusively for writing data to files.
- Default Mode: Opens files in output mode (
ios::out). If the target file does not exist, it creates a new file. If it already exists, it truncates (clears) the file contents by default.
- 2.
ifstream(Input File Stream):- Purpose: Used exclusively for reading data from files.
- Default Mode: Opens files in input mode (
ios::in). If the specified file does not exist, the opening operation fails.
- 3.
fstream(General File Stream):- Purpose: A versatile, multi-purpose class capable of performing both reading and writing operations on the same file concurrently.
- Default Mode: Requires explicit specification of file opening modes (e.g.,
ios::in | ios::out | ios::app).
Code Summary:
#fstream
#iostream
using namespace std;
int main() {
ofstream out("test.txt"); // Writes to file
out << "Hello World";
out.close();
ifstream in("test.txt"); // Reads from file
string s;
in >> s;
in.close();
fstream file("test.txt", ios::in | ios::out | ios::app); // Read/Write/Append
file << "\nAppended Line";
file.close();
return 0;
}
Q: Define base class and derived class with a simple syntax example.
Easy Answer:
A base class (also known as parent or superclass) is the existing class whose properties and behaviors are inherited. A derived class (also known as child or subclass) is the newly created class that inherits features from the base class and can add its own unique members.
Syntax Example:
class Animal { // Base Class
public:
void eat() { /* code */ }
};
class Dog : public Animal { // Derived Class
public:
void bark() { /* code */ }
};
Q: What do you understand by multiple inheritance?
Easy Answer:
Multiple inheritance is an OOP feature where a single derived class inherits members and characteristics from more than one base class. While it provides high flexibility by combining features from multiple domains, it can introduce complexities like member ambiguity and the famous "Diamond Problem" if base classes share common ancestors.
Syntax Example:
class Engine { /* ... */ };
class Body { /* ... */ };
class Car : public Engine, public Body { /* ... */ }; // Multiple Inheritance
Q: Explain the diamond problem in inheritance and how virtual inheritance solves it.
Easy Answer:
The diamond problem occurs in multiple inheritance when a derived class inherits from two separate classes that both inherit from a common base class. This creates two distinct copies of the grand-base class inside the final derived object, causing ambiguity when accessing its members.
Virtual inheritance solves this by ensuring that only one shared instance of the common base class is inherited, regardless of how many paths lead to it.
Syntax Solution:
class Base { public: int x; };
class Derived1 : virtual public Base { }; // Virtual inheritance
class Derived2 : virtual public Base { };
class Final : public Derived1, public Derived2 { }; // Only 1 copy of 'x' exists
Q: What is pure virtual function? Give its syntax.
Easy Answer:
A pure virtual function is a virtual function with no implementation body in the base class; it is assigned the value 0. It acts as a mandatory placeholder that forces all concrete derived classes to override and implement their own version of the function.
Syntax:
class Shape {
public:
virtual void draw() = 0; // Pure Virtual Function
};
Q: Can a constructor be virtual in C++? Justify your answer.
Easy Answer:
No, a constructor cannot be virtual. Justification: Virtual functions rely on a virtual table (vtable) and a pointer (vptr) that is initialized inside the object only after the object is created. Since a constructor's job is to create and initialize the object in the first place, calling a virtual constructor makes no logical sense because the mechanism required to support virtual calls does not yet exist.
Q: What is operator overloading? List operators that cannot be overloaded.
Easy Answer:
Operator overloading gives custom, user-defined classes the ability to respond to standard C++ operators (like +, -, ==). This improves code readability and intuitive usage.
Operators that CANNOT be overloaded in C++:
- Scope resolution operator (
::) - Member selection operator (
.) - Member pointer selector (
.*) - Conditional/Ternary operator (
?:) - Sizeof operator (
sizeof) - Type identification operator (
typeid)
Q: Why do we need a virtual destructor?
Easy Answer:
A virtual destructor is needed to ensure proper cleanup and prevent memory leaks when deleting a derived class object through a base class pointer. If a base class destructor is non-virtual, deleting a derived object via a base pointer only calls the base destructor, leaving the derived class's allocated resources uncleared.
Syntax:
class Base {
public:
virtual ~Base() {} // Virtual Destructor
};
Q: What is the purpose of the 'noexcept' specifier in C++ exceptions?
Easy Answer:
The noexcept specifier promises the compiler that a specific function will not throw any exceptions. It enables the compiler to perform aggressive optimizations (such as omitting exception-handling stack unwind structures), resulting in faster and more efficient machine code execution.
Syntax Example:
void fastFunction() noexcept {
// Guaranteed not to throw exceptions
}
Q: How do you open a file in append mode using C++ file streams?
Easy Answer:
To open a file in append mode—where new data is written to the end of the file without overwriting existing content—you use the ios::app flag combined with an ofstream or fstream object.
Code Example:
#fstream
using namespace std;
int main() {
ofstream outFile("data.txt", ios::app);
outFile << "Appending new text record.\n";
outFile.close();
return 0;
}
Q: What is the difference between read() and write() functions in binary file handling?
Easy Answer:
In binary file handling:
write()function: Used byofstreamorfstreamto transfer a block of raw bytes from memory (variables, structures, objects) directly onto the binary file storage.read()function: Used byifstreamorfstreamto retrieve raw byte streams from a binary file and load them back into computer memory variables.
Both functions take two parameters: a character pointer cast of the data address (char*) and the size in bytes (sizeof()).
Long Question: Discuss the different types of inheritance supported by C++ with appropriate programming examples for each.
Simple Introduction & Definition
Inheritance is one of the foundational pillars of Object-Oriented Programming (OOP) in C++. It allows a new class, known as the derived or child class, to adopt the properties, attributes, and behaviors (member functions) of an existing class, known as the base or parent class. Think of inheritance in real life like family traits: a child inherits physical features and mannerisms from their parents, but they can also develop their own unique skills and traits. In C++, inheritance promotes code reusability, reduces redundancy, and establishes a logical, hierarchical relationship between different classes. C++ supports several types of inheritance based on how many base and derived classes are involved, and the manner in which they are connected.
1. Single Inheritance
In single inheritance, a single derived class is created from a single base class. This is the simplest and most common form of inheritance.
- Structure: One Parent $\rightarrow$ One Child.
- Real-world Example: A base class named
Animalcan be inherited by a derived class namedDog. - Benefit: Straightforward implementation without complex hierarchy logic.
2. Multiple Inheritance
Multiple inheritance occurs when a single derived class inherits properties and behaviors from two or more base classes simultaneously.
- Structure: Multiple Parents $\rightarrow$ One Child.
- Real-world Example: A class
TeachingAssistantmight inherit from both aTeacherclass and aStudentclass. - Caution: Can lead to the "Diamond Problem" if base classes share common member names.
3. Multilevel Inheritance
In multilevel inheritance, a derived class is created from another derived class, forming a chain or generational hierarchy.
- Structure: Grandparent $\rightarrow$ Parent $\rightarrow$ Child.
- Real-world Example:
Vehicle$\rightarrow$FourWheeler$\rightarrow$Car. - Benefit: Allows gradual and specialized extension of features down the line.
4. Hierarchical Inheritance
Hierarchical inheritance features multiple derived classes inheriting from a single base class. It represents a tree-like structure.
- Structure: One Parent $\rightarrow$ Multiple Children.
- Real-world Example: A base class
Shapecan be inherited byCircle,Rectangle, andTriangle. - Benefit: Centralizes common attributes in one place while allowing diverse specializations.
5. Hybrid (Virtual) Inheritance
Hybrid inheritance is a combination of two or more types of inheritance (e.g., combining multilevel and multiple inheritance). It often creates ambiguous situations.
- Structure: Complex combinations forming diamond shapes.
- Real-world Example: Class A is inherited by B and C, and both B and C are inherited by D.
- Solution: Uses the
virtualkeyword to prevent duplicate copies of base class members.
6. Public Inheritance Mode
Public inheritance is the most commonly used mode where the public and protected members of the base class retain their accessibility levels in the derived class.
- Public members stay public.
- Protected members stay protected.
- Private members remain inaccessible directly.
7. Protected Inheritance Mode
In protected inheritance, the public and protected members of the base class become protected members of the derived class.
- Restricts external access while keeping members available to further derived classes.
8. Private Inheritance Mode
In private inheritance, public and protected members of the base class become private members of the derived class.
- Internal implementation details of the base class are hidden from the outside world.
9. Comprehensive C++ Code Example Demonstrating Inheritance Types
#include <iostream>
using namespace std;
// Base Class for Single Inheritance
class Animal {
public:
void eat() {
cout << "This animal eats food." << endl;
}
};
// Derived Class (Single Inheritance)
class Dog : public Animal {
public:
void bark() {
cout << "The dog barks: Woof! Woof!" << endl;
}
};
int main() {
Dog myDog;
myDog.eat(); // Inherited from Animal
myDog.bark(); // Defined in Dog
return 0;
}
10. Advantages of Inheritance in Software Engineering
- Code Reusability: Write once, use and extend anywhere.
- Maintainability: Bug fixes in the base class automatically propagate (where appropriate).
- Extensibility: New features can be added without modifying existing tested code.
Easy Summary / Exam Conclusion
Inheritance is a powerful mechanism in C++ that models real-world taxonomic relationships. By supporting single, multiple, multilevel, hierarchical, and hybrid inheritance, C++ gives developers immense flexibility in structuring code. Understanding access specifiers (public, protected, private) is vital for secure and robust OOP design. In exams, always support your text with a clear syntax example and clean structure diagrams.
Long Question: Explain runtime polymorphism in detail. Write a complete C++ program using a base class 'Shape' and derived classes 'Circle' and 'Rectangle' to demonstrate dynamic binding via virtual functions.
Simple Introduction & Definition
Polymorphism means "many forms." In object-oriented programming, polymorphism allows a single interface to represent different underlying forms or data types. There are two main types: compile-time polymorphism (function overloading) and runtime polymorphism (dynamic method dispatch). Runtime polymorphism occurs when a derived class overrides a method of its base class. When a function is called through a base class pointer or reference, C++ determines which function to execute *at runtime* rather than at compile time. This dynamic behavior is achieved using virtual functions.
1. Concept of Virtual Functions
A virtual function is a member function declared within a base class and re-defined (overridden) by a derived class. When you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual function for that object and execute the derived class's version of the function.
- Declared using the
virtualkeyword in the base class. - Instructs the compiler to perform dynamic binding.
2. Compile-Time vs. Runtime Binding
Normally, C++ uses static binding (early binding), where function calls are resolved during compilation based on pointer types. Runtime polymorphism uses dynamic binding (late binding), resolving calls based on the actual object content in memory during execution.
- Static binding is fast but rigid.
- Dynamic binding enables flexible, extensible object-oriented architectures.
3. The Role of Base Class Pointers
A pointer of type base class can point to objects of its derived classes. This is a fundamental rule in C++ type compatibility that powers polymorphism.
- Example:
Shape *ptr; Circle c; ptr = &c; - Allows uniform treatment of diverse objects through a common collection or interface.
Part 4: Solved Multiple Choice Questions (MCQs)
MCQ #1 Which type of inheritance allows a class to inherit from more than one base class?
Single InheritanceMultilevel InheritanceMultiple InheritanceHierarchical InheritanceMCQ #2 What is the primary purpose of using virtual functions in C++?
To achieve compile-time polymorphismTo achieve runtime polymorphismTo overload operatorsTo handle exceptionsMCQ #3 Which of the following classes cannot be instantiated directly?
Derived ClassAbstract ClassBase ClassInline ClassMCQ #4 Which keyword is used to handle exceptions in C++?
trycatchthrowAll of the aboveMCQ #5 Which operator cannot be overloaded in C++?
+-::=MCQ #6 Which stream class is used for writing output to files in C++?
ifstreamofstreamfstreamiostreamMCQ #7 What is function overriding?
Defining multiple functions with the same name in the same scopeRedefining a base class function in a derived class with the same signatureChanging the return type of a functionUsing default arguments in a functionMCQ #8 Which mode opens a file for appending data at the end without overwriting existing content?
ios::inios::outios::appios::truncMCQ #9 What makes a virtual function a 'pure' virtual function?
It returns zeroIt is declared with '= 0'It has no return typeIt is privateMCQ #10 Which inheritance type represents a 'Diamond Problem' scenario?
MultilevelHierarchicalHybridSingleMCQ #11 What is the default access specifier for members of a class in C++?
publicprotectedprivatefriendMCQ #12 Which function is used to check if the end of a file has been reached?
bad()eof()fail()good()MCQ #13 What type of polymorphism is implemented using function overloading?
Runtime polymorphismCompile-time polymorphismDynamic polymorphismSubtype polymorphismMCQ #14 Which keyword is used to catch any type of exception in C++?
catch (int)catch (char)catch (...)catch (exception)MCQ #15 Which header file is essential for file I/O operations in C++?
<iostream><fstream><iomanip><exception>