π Lecture 28 β Virtual Functions
π Overview: This lecture introduces virtual functions in C++ to solve a classic OOP problem: how to call the correct derived class method when using a base class pointer array. It demonstrates why a simple inheritance-based approach fails and how virtual functions enable automatic runtime method dispatch, eliminating the need for complex type-checking code.
ποΈ Topics Covered
The lecture begins with a problem statement about drawing different geometric shapes from an array of Shape pointers. It presents a Shape hierarchy with Line, Circle, and Triangle classes, then shows the failure of a naive inheritance approach where the base class draw() method is always called. The lecture explores solution 1 involving switch/if-else logic with type checking and explains why this leads to delocalized, unmaintainable code. Finally, it introduces virtual functions as the proper OOP solution, demonstrates their implementation in the Shape hierarchy, and contrasts static versus dynamic binding.
π Lecture Summary
Virtual Functions
Problem Statement: Develop a function that can draw different types of geometric shapes from an array
The lecture presents a Shape Hierarchy with a base Shape class and derived classes Line, Circle, and Triangle. Each derived class has its own draw() and calcArea() methods. The goal is to implement a function that takes a Shape pointer array (Shape * []) and its size as parameters, then draws the appropriate shape for each element.
The key idea is that a base class pointer can store pointers to any of its publicly derived classes (IS-A relationship). This allows us to avoid complex code that checks class types individually. Instead, we can use a single function call in a loop:
void drawShapes(Shape *array[], int size) {
for (int i = 0; i < size; i++)
array[i]->draw(); // Should work for Line, Circle, Triangle
}
Implementation
A general Shape class is created with a draw() method that prints "Shape\n" and a calcArea() method returning 0. Derived classes Line, Circle, and Triangle override draw() with their own implementations.
In main(), objects of Line, Circle, and Triangle are created dynamically and stored in a Shape pointer array:
Shape* _shape[10];
Point p1(0, 0), p2(10, 10);
shape[1] = new Line(p1, p2);
shape[2] = new Circle(p1, 15);
When drawShapes() is called with this array, the output shows "Shape" repeatedly instead of the correct class names (Line, Circle, Triangle).
Why does this happen? The problem is that the static type of the array is Shape*, so the draw() method of the Shape class is always called, regardless of whether the actual pointer stored is a Line, Circle, Triangle, or Shape pointer.
Solution 1: Type Checking with Switch/If-Else
One solution modifies drawShapes() to determine the object type and call the appropriate method:
void drawShapes(Shape* _shape[], int size) {
for (int i = 0; i < size; i++) {
switch (_shape[i]->getType()) {
case 'L':
static_cast<Line*>(_shape[i])->draw();
break;
case 'C':
static_cast<Circle*>(_shape[i])->draw();
break;
// ...
}
}
}
Equivalent if-else logic:
if (_shape[i]->getType() == 'L')
static_cast<Line*>(_shape[i])->draw();
else if (_shape[i]->getType() == 'C')
static_cast<Circle*>(_shape[i])->draw();
Sample Output: Line, Circle, Triangle, Circle...
While this approach works, it has serious Problems:
π Delocalized Code: If we need another function like printArea(), we must write the same switch/if-else logic again:
void printArea(Shape* _shape[], int size) {
for (int i = 0; i < size; i++) {
switch (_shape[i]->getType()) {
case 'L':
static_cast<Line*>(_shape[i])->calcArea();
break;
case 'C':
static_cast<Circle*>(_shape[i])->calcArea();
break;
// ...
}
}
}
This leads to two main consequences:
- Writing the same code repeatedly may produce errors if the programmer forgets to add switch cases.
- Adding a new Shape class requires adding a new case in all functions using this logicβif even one function is missed, the program shows incorrect output.
Such code is very hard to maintain.
Solution? We need a mechanism that can select the message target (class) automaticallyβwithout switch statements.
Polymorphism Revisited
In the OO model, polymorphism means different objects can behave in different ways for the same message (stimulus). Consequently, the sender of a message does not need to know the exact class of the receiver.
With correct inheritance structure and polymorphism, adding more shapes should work automaticallyβthe appropriate draw() method should be called without modifying existing code. This is the benefit of OOP:
void drawShapes(Shape *array[], int size) {
for (int i = 0; i < size; i++)
array[i]->draw(); // Automatically calls correct class's draw()
}
To achieve this functionality, we need the concept of virtual functionsβmaking those functions virtual in the base class that will be implemented by derived classes according to their requirements.
Virtual Functions: Definition and Implementation
π Virtual Functions β Functions that achieve automatic runtime target class selection, eliminating the need for complex switch/if-else type-checking code.
Key characteristics:
- The target class of a virtual function call is determined at run-time automatically
- In C++, we declare a function virtual by preceding the function header with the keyword
virtual
Virtual Functions in the Shape Hierarchy
Functions that need to be overridden by derived classes are made virtual in the base class:
class Shape {
// ...
virtual void draw();
virtual int calcArea();
};
Derived classes then override these virtual functions:
class Line : public Shape {
// ...
virtual void draw() { cout << "Line...\n"; }
};
class Circle : public Shape {
// ...
virtual void draw() { cout << "Circle...\n"; }
virtual int calcArea();
};
class Triangle : public Shape {
// ...
virtual void draw() { cout << "Triangle...\n"; }
virtual int calcArea();
};
With virtual functions, the drawShapes() implementation becomes simple and works correctly:
void drawShapes(Shape* _shape[], int size) {
for (int i = 0; i < size; i++) {
_shape[i]->draw(); // Automatically calls correct class
}
}
Sample Output: Line, Circle, Triangle, Circle...
Similarly, printArea() works without switch logic:
void printArea(Shape* _shape[], int size) {
for (int i = 0; i < size; i++) {
cout << _shape[i]->calcArea();
cout << endl;
}
}
π‘ Why this matters: Virtual functions automatically determine which class's method to call at runtime, making code extensible and maintainable. Adding a new shape class works without modifying existing functions.
Static vs Dynamic Binding
π Static Binding β The target function for a call is selected at compile time.
Example:
Line _line;
_line.draw(); // Always Line::draw will be called (determined at compile time)
π Dynamic Binding β The target function for a call is selected at run time.
Example:
Shape* _shape = new Line();
// Without virtual: Shape::draw() is called (static binding on static type Shape*)
// With virtual: Line::draw() is called (dynamic binding at runtime)
When draw() is not virtual, the call _shape->draw() invokes Shape::draw() because the compiler uses the static type Shape*.
When draw() is virtual in the base Shape class, the call _shape->draw() invokes Line::draw() because the runtime determines the actual object type and calls the appropriate overridden method.
β Key Takeaways
This lecture teaches that virtual functions are the correct OOP mechanism for achieving runtime polymorphism, allowing base class pointers to correctly call derived class methods without manual type checking. Students must understand that static binding selects methods at compile time based on pointer/reference type, while dynamic binding (via virtual functions) selects methods at runtime based on the actual object type. The delocalized code problem with switch/if-else approaches makes code unmaintainable and error-prone when adding new derived classes. Virtual functions eliminate this problem by automatically routing method calls to the appropriate class implementation. Remember that declaring a function virtual in the base class with the virtual keyword enables dynamic binding for that function throughout the inheritance hierarchy.
π§ Quick Revision Questions
-
Why did the naive inheritance approach (without virtual functions) print "Shape" instead of "Line", "Circle", or "Triangle" when calling draw() through a Shape pointer array?
-
What are the two main problems with using switch/if-else type-checking to call the correct derived class method?
-
How does declaring a function as
virtualin the base class change how the compiler handles function calls through base class pointers? -
What is the difference between static binding and dynamic binding? Give one example of each from the shape hierarchy.
-
In the Shape hierarchy, if a new class
Rectangleis added with its owndraw()andcalcArea()methods, would the existingdrawShapes()andprintArea()functions work without modification? Explain why or why not.
π Lecture 29 β Abstract Classes, Virtual Destructors, and Dynamic Dispatch
π Overview: This lecture completes the discussion on polymorphism by introducing abstract classes and pure virtual functions as essential tools for designing class hierarchies. It also addresses the critical problem of memory leaks when deleting derived objects through base pointers and explains how virtual destructors solve this. Finally, it demystifies how the compiler actually implements polymorphic behavior using virtual tables (vTables) and dynamic dispatch.
ποΈ Topics Covered
The lecture covers abstract classes versus concrete classes, pure virtual functions and how to declare them in C++, the Shape class hierarchy with abstract intermediate classes like Quadrilateral, the problem of memory leaks when destructors are non-virtual, virtual destructors and their proper destruction order, two usage patterns for virtual functions (inheriting interface alone vs. inheriting interface and implementation), and finally the internal mechanism of vTables and dynamic dispatch.
π Lecture Summary
Previous Lecture Review
The main concept of Polymorphism is that the same method can behave differently according to the object with respect to which it has been called. Related classes with similar functionality are combined in a class hierarchy (Shape, Line, Circle, Triangle) where draw and calcArea methods show polymorphic behavior. This type of polymorphism is achieved using virtual functions. The advantage is that the sender simply passes a method call and the appropriate method is called automatically, as demonstrated by using a for loop to draw all shapes using a shape pointer array. Without virtual functions, achieving the same functionality requires complex, delocalized switch statements.
π‘ Why this matters: Virtual functions enable object-oriented code that is extensible and maintainable β new shape classes can be added without modifying existing drawing code.
29.1. Abstract Classes
An Abstract Class represents an abstract concept with no direct real-world existence. In the Shape class hierarchy, there is no real object named "Shape" β only specific shapes like Line, Circle, or Triangle exist. Abstract classes cannot be instantiated; they are used only for inheriting interface and/or implementation. The actual behavior (like draw and calcArea) is realized in derived classes.
29.2. Concrete Classes
Concrete Classes implement a concrete concept. They can be instantiated and may inherit from an abstract class or another concrete class. All classes studied so far in the course have been concrete classes.
29.3. Abstract Classes in C++
In C++, a class can be made abstract by making one or more of its functions pure virtual. Conversely, a class with no pure virtual functions is a concrete class (its objects can be instantiated).
29.4. Pure Virtual Functions
A Pure Virtual Function represents an abstract behavior and may have no implementation. For example, the draw method in Shape class represents abstract behavior since Shape itself has no real-world existence. A function is declared pure virtual by following its header with = 0:
virtual void draw() = 0;
A class having at least one pure virtual function becomes abstract and cannot be instantiated:
class Shape {
public:
virtual void draw() = 0;
};
Shape s; // Error! Cannot instantiate abstract class
π Definition β Pure Virtual Function: A virtual function declared with = 0 that has no implementation in the base class, forcing derived classes to override it.
π Formula: virtual returnType functionName(parameters) = 0; β The function is purely abstract; only its interface is inherited.
π Example: virtual void draw() = 0; in Shape. Line, Circle, and Triangle must each provide their own implementation of draw().
29.5. Shape Hierarchy
A derived class of an abstract class remains abstract until it provides implementation for all pure virtual functions. Abstract classes are present at the root or near the root of the class hierarchy, while concrete classes are near the leaves.
In the hierarchy: Shape (abstract) β Quadrilateral (abstract, inherits from Shape but does not override draw) β Rectangle (concrete, overrides draw).
class Quadrilateral : public Shape {
// No overriding draw() method β Quadrilateral remains abstract
};
Quadrilateral q; // Error! Cannot instantiate abstract class
class Rectangle : public Quadrilateral {
public:
virtual void draw() { // draw is still virtual throughout hierarchy
// function body
}
};
Rectangle r; // OK β Rectangle is concrete
π‘ Why this matters: At least one concrete class must exist at a leaf of the hierarchy; otherwise, the entire hierarchy would be uninstantiable and useless.
29.6. Virtual Destructors
When a derived class object is deleted through a base class pointer, the destructor is called according to the static type of the pointer (the pointer's declared type, not the object's actual type). If the base class destructor is not virtual, only the base class destructor runs, leaving the derived parts of the object undeleted β causing a memory leak.
Example of the problem:
class Shape {
public:
~Shape() { cout << "Shape destructor called\n"; }
};
class Rectangle : public Quadrilateral {
public:
~Rectangle() { cout << "Rectangle destructor called\n"; }
};
int main() {
Shape* pShape = new Rectangle();
delete pShape; // Only "Shape destructor called" β memory leak!
return 0;
}
Output: Shape destructor called β only the base part is destroyed; the Rectangle part remains allocated.
The Solution β Virtual Destructors:
Make the base class destructor virtual, just as we made draw virtual:
class Shape {
public:
virtual ~Shape() { cout << "Shape destructor called\n"; }
};
class Rectangle : public Quadrilateral {
public:
virtual ~Rectangle() { cout << "Rectangle destructor called\n"; }
};
int main() {
Shape* pShape = new Rectangle();
delete pShape; // All destructors called in correct order
return 0;
}
Output:
Rectangle destructor called
Quadrilateral destructor called
Shape destructor called
Now, the derived class destructor runs first, then the base class destructor β ensuring the complete object is properly destroyed with no memory leak.
π Definition β Virtual Destructor: A destructor declared with the virtual keyword in a base class, ensuring that when an object is deleted through a base class pointer, the correct derived class destructor is called first, followed by all base class destructors in reverse order of inheritance.
π Example: virtual ~Shape() {} ensures that deleting through Shape* correctly calls ~Rectangle(), ~Quadrilateral(), and then ~Shape().
29.7. Virtual Functions β Usage
Virtual functions are used in two ways:
-
Inherit interface AND implementation (Simple Virtual Functions): Both base and derived classes have implementations. The base provides a default that derived classes may override.
-
Inherit interface ONLY (Pure Virtual Functions): Only derived classes provide implementation; the base class has no implementation (or a minimal one).
Example combining both:
class Shape {
public:
virtual void draw() = 0; // pure virtual β inherit interface only
virtual float calcArea() { // simple virtual β inherit interface and default implementation
return 0;
}
};
draw()is pure virtual because every shape must draw itself β each concrete derived class must override it.calcArea()is simple virtual because some shapes (like Line and Point) have no area β they inherit the default implementation that returns 0, while shapes like Circle and Triangle override it.
29.8. V Table (Virtual Table)
The compiler keeps track of virtual functions using a Virtual Function Table (vTable) for each class that has virtual functions. A vTable contains a pointer for each virtual function in the class.
How vTables work with the example:
int main() {
Point p1(10,10), p2(30,30);
Shape* pShape;
pShape = new Line(p1, p2);
pShape->draw();
pShape->calcArea();
return 0;
}
- When the code is compiled, vTables and implementation code for virtual and non-virtual functions are generated for all classes.
- Each class gets its own vTable:
Shape vTable(with pointers to Shape'sdrawandcalcArea) andLine vTable(with pointers to Line'sdrawandcalcArea). - When a
Lineobject is created, it contains a hidden pointer toLine vTable. - The
Shape* pShapestores the address of the Line object.
π Definition β vTable: A per-class table created by the compiler containing function pointers for every virtual function in the class. Each object of a class with virtual functions carries a hidden pointer to its class's vTable.
29.9. Dynamic Dispatch (Dynamic Binding)
Dynamic Dispatch occurs in the case of virtual functions. For non-virtual functions, the compiler simply generates code to call the function directly. For virtual functions, the compiler generates code to:
- Access the object
- Access the associated vTable (through the object's hidden vTable pointer)
- Call the appropriate function (the one pointed to by the vTable entry)
This is why pShape->draw() calls Line::draw() even though pShape is declared as Shape* β because at runtime, the vTable of the actual object (Line) is used.
β Key Takeaways
Abstract classes with pure virtual functions are essential for designing polymorphic class hierarchies where the base class represents a general concept with no physical instantiation. Every class with virtual functions should have a virtual destructor to prevent memory leaks when deleting derived objects through base class pointers β this ensures destructors run in the correct order (most derived first, base last). Virtual functions come in two flavors: simple virtual (inherit interface AND default implementation) and pure virtual (inherit interface only, forcing every concrete derived class to implement the method). The compiler implements polymorphism through vTables and dynamic dispatch, which adds both memory and processing overhead β so virtual functions should be used with care, balancing the need for extensibility against performance requirements.
π§ Quick Revision Questions
-
What is the difference between an abstract class and a concrete class? Can you instantiate an object of an abstract class?
-
How do you declare a pure virtual function in C++? Write the syntax for a pure virtual function
draw()inside aShapeclass. -
What problem occurs if you delete a derived class object through a base class pointer and the base class destructor is NOT virtual? What is the resulting output?
-
What is a vTable and how does it enable dynamic dispatch? What three steps does the compiler generate code for when calling a virtual function?
-
Explain the difference between "inheriting interface only" and "inheriting interface and implementation" using virtual functions. Give a concrete example from the Shape hierarchy.
π Lecture 30 β Polymorphism β Case Study: A Simple Payroll Application
π Overview: This lecture demonstrates a practical implementation of polymorphism using a payroll system for different employee types. It also warns against using arrays polymorphically, explaining the critical distinction between pointer arrays and object arrays when working with polymorphic behavior.
ποΈ Topics Covered
The lecture covers a complete case study of a payroll application using polymorphism with an Employee base class and three derived classes (SalariedEmp, HourlyEmp, CommEmp). It then revisits the Shape hierarchy to demonstrate the dangerous consequences of treating object arrays polymorphically, explaining why pointer arrays must be used instead.
π Lecture Summary
30.1. Polymorphism β Case Study: A Simple Payroll Application
The lecture presents a payroll application for a company with three employee types: salaried employees, hourly employees, and commissioned employees. The system uses an array of Employee pointers to calculate salaries polymorphically and generate reports.
The Employee class is an abstract base class with a pure virtual function calcSalary(). It contains private members name and taxRate, with a constructor that initializes these values.
π Definition β Abstract Base Class: A base class that cannot be instantiated directly, containing at least one pure virtual function.
class Employee {
private:
String name;
double taxRate;
public:
Employee(String&, double);
String getName();
virtual double calcSalary() = 0; // pure virtual function
};
π Formula: calcSalary() β Returns net salary after tax deduction.
The SalariedEmp class inherits from Employee and calculates salary as salary minus tax.
π Example: SalariedEmp("Aamir", 0.05, 15000) β tax = 15000 Γ 0.05 = 750 β net salary = 15000 β 750 = 14250
double SalariedEmp::calcSalary() {
double tax = salary * taxRate;
return salary β tax;
}
The HourlyEmp class calculates salary based on hours worked and hourly rate.
π Example: HourlyEmp("Faakhir", 0.06, 160, 50) β grossPay = 160 Γ 50 = 8000 β tax = 8000 Γ 0.06 = 480 β net salary = 7520
double HourlyEmp::calcSalary() {
double grossPay = hours * hourlyRate;
double tax = grossPay * taxRate;
return grossPay β tax;
}
The CommEmp class calculates salary based on sales and commission rate.
π Example: CommEmp("Fuaad", 0.04, 150000, 10) β grossPay = 150000 Γ 0.10 = 15000 β tax = 15000 Γ 0.04 = 600 β net salary = 14400
double CommEmp::calcSalary() {
double grossPay = sales * commRate;
double tax = grossPay * taxRate;
return grossPay β tax;
}
The generatePayroll function takes an array of Employee pointers and iterates through them, calling getName() and calcSalary() polymorphically:
void generatePayroll(Employee* emp[], int size) {
for (int i = 0; i < size; i++) {
cout << emp[i]->getName() << '\t' << emp[i]->calcSalary() << '\n';
}
}
π‘ Why this matters: The same calcSalary() call on a base class pointer invokes different implementations depending on the actual derived object type, demonstrating the power of polymorphism.
Important point: Polymorphism always works with pointers of class objects, not with actual objects.
30.2. Shape Hierarchy Revisited
This section demonstrates why polymorphism fails with object arrays. The Shape class hierarchy is revisited with a non-abstract Shape class:
class Shape {
public:
Shape();
virtual void draw() { cout << "Shape\n"; }
virtual int calcArea() { return 0; }
};
class Line : public Shape {
public:
Line(Point p1, Point p2);
void draw() { cout << "Line\n"; }
};
When an array of Shape objects is passed to drawShapes(), it works correctly:
void drawShapes(Shape _shape[], int size) {
for (int i = 0; i < size; i++) {
_shape[i].draw();
}
}
However, when an array of Line objects is passed to the same function, runtime error occurs:
int main() {
Line _line[10];
_line[0] = Line(p1, p2);
drawShapes(_line, 10); // PROBLEM!
return 0;
}
π Definition β Array Slicing: When a derived class object is assigned to a base class array element, only the base class portion is copied, losing derived class data and causing incorrect memory calculations.
The compiler calculates the address of the next element using sizeof(Shape), but the actual array contains Line objects of a different size. This leads to incorrect address calculation and abnormal program termination.
π Example: If Shape object size = 10 bytes and Line object size = 15 bytes, and Line array starts at address 0000, the compiler expects next object at address 0010, but the actual next Line object is at address 0015, causing a runtime error.
The correct approach uses a pointer array:
void drawShapes(Shape* _shape[], int size) {
for (int i = 0; i < size; i++) {
_shape[i]->draw(); // Correct polymorphic behavior
}
}
π‘ Why this matters: Since all pointers are 4 bytes on 32-bit systems, the array element size is constant regardless of what the pointers point to, ensuring correct address calculation.
β Key Takeaways
The lecture demonstrates that polymorphism effectively solves the payroll problem by allowing a single function to handle different employee types through virtual functions. However, the critical warning is that arrays should never be used polymorphically because element address calculation depends on array type size, and derived class objects have different sizes than base class objects. Always use arrays of base class pointers (not objects) to achieve correct polymorphic behavior. The pointer array ensures uniform element size (4 bytes per pointer) regardless of the actual object type, while object arrays cause memory errors due to incorrect size calculations.
π§ Quick Revision Questions
- Why must the Employee class have
calcSalary()as a pure virtual function? - What would happen if we passed an array of
HourlyEmpobjects instead of an array ofEmployee*pointers togeneratePayroll()? - In the Shape hierarchy example, why does passing
Line[10]todrawShapes(Shape[], int)cause a runtime error? - What is the formula for calculating the address of the i-th element in an array, and why does this cause problems with polymorphic object arrays?
- How many bytes does each pointer occupy in a pointer array, and why does this ensure correct polymorphic behavior?
π Lecture 31 β Multiple Inheritance
π Overview: This lecture focuses on multiple inheritance in C++, where a class inherits from more than one base class. It covers the syntax, behavior, and common problems like ambiguity from duplicate function names, and introduces virtual inheritance as a solution to the diamond problem.
ποΈ Topics Covered
The lecture begins with the syntax of multiple inheritance and how derived class objects can use functions from all base classes. It then discusses pointer substitution with multiple base classes and the restrictions involved. The primary problems covered are ambiguous function calls when two base classes share the same function signature, and the "diamond" problem from multi-level multiple inheritance leading to duplicate base class subobjects. Finally, virtual inheritance is introduced as the solution to ensure a single shared base class instance.
π Lecture Summary
31.1. Multiple Inheritance
A class in C++ can inherit from more than one base class. The syntax lists all base classes separated by commas, each with its own access specifier (e.g., public, private, protected). The derived class inherits all the data members and member functions from each base class. An object of the derived class can perform tasks that objects of any of the base classes can perform. When using public multiple inheritance, a pointer to any of the base classes can point to a derived class object, but a pointer of one base class cannot be used to call a function belonging to a different base class.
π Definition β Multiple Inheritance: A feature in C++ where a class can inherit from more than one base class simultaneously.
class Phone: public Transmitter, public Receiver
// Phone inherits from both Transmitter and Receiver
{ ... };
class Mermaid: private Woman, private Fish
// Private inheritance means derived classes of Mermaid cannot access Woman or Fish members
{ ... };
π Example: A Phone object can call Transmit() (from Transmitter) and Receive() (from Receiver).
int main(){
Phone obj;
obj.Transmit();
obj.Receive();
return 0;
}
π Definition β Pointer Substitution with Multiple Inheritance: In public multiple inheritance, a derived class object can be pointed to by pointers of its base class types, but each base pointer can only access members of that specific base class.
int main(){
Phone obj;
Transmitter * tPtr = &obj; // Valid
Receiver * rPtr = &obj; // Valid
// tPtr->Receive(); // Error: tPtr is of type Transmitter*
return 0;
}
31.2. Problems in Multiple Inheritance
If two or more base classes have a member function with the same signature (name and parameters), the derived class will inherit multiple copies of that function. Calling this function on an object of the derived class results in a compile-time ambiguity error because the compiler does not know which base class's version to invoke. This ambiguity can also arise in multi-level multiple inheritance, known as the diamond problem, where a class inherits from two intermediate classes that both inherit from the same base class. This results in the final derived class having two implicit subobjects of the topmost base class.
π Definition β Ambiguity in Multiple Inheritance: A compile-time error that occurs when the compiler cannot determine which base class's member function to call because two or more base classes have a function with the same signature.
π Example: LandVehicle and WaterVehicle both have a GetMaxLoad() function.
class LandVehicle{
public:
int GetMaxLoad();
};
class WaterVehicle{
public:
int GetMaxLoad();
};
class AmphibiousVehicle: public LandVehicle, public WaterVehicle { };
int main(){
AmphibiousVehicle obj;
// obj.GetMaxLoad(); // Error: ambiguous call
return 0;
}
π Example (Solution): The programmer must explicitly specify the class name using the scope resolution operator.
int main(){
AmphibiousVehicle obj;
obj.LandVehicle::GetMaxLoad();
obj.WaterVehicle::GetMaxLoad();
return 0;
}
π Definition β The Diamond Problem: A specific ambiguity issue in multiple inheritance where a class inherits from two classes that both inherit from a single common base class, leading to two copies of the common base class's members in the final derived class.
π Example: AmphibiousVehicle inherits from LandVehicle and WaterVehicle, which both inherit from Vehicle.
class Vehicle{
public:
int GetMaxLoad();
};
class LandVehicle : public Vehicle{ };
class WaterVehicle : public Vehicle{ };
class AmphibiousVehicle: public LandVehicle, public WaterVehicle { };
int main(){
AmphibiousVehicle obj;
// obj.GetMaxLoad(); // Error: ambiguous
// obj.Vehicle::GetMaxLoad(); // Error: Vehicle is still ambiguous because there are two copies of it
obj.LandVehicle::GetMaxLoad(); // Valid: explicit path to one Vehicle copy
return 0;
}
π‘ Why this matters: The diamond problem leads to memory duplication and ambiguity, making it hard to determine which base subobject to use. Data members must also be used with care.
class Vehicle{
protected:
int weight;
};
class LandVehicle : public Vehicle{ };
class WaterVehicle : public Vehicle{ };
class AmphibiousVehicle: public LandVehicle, public WaterVehicle{
public:
AmphibiousVehicle(){
LandVehicle::weight = 10; // Refers to one copy of weight
WaterVehicle::weight = 10; // Refers to a different copy of weight
}
};
In this case, the AmphibiousVehicle object contains two separate weight members.
31.3. Virtual Inheritance
Virtual inheritance is the solution to the diamond problem. When a base class is declared as virtual in the inheritance list of intermediate classes, the compiler ensures that only one copy of its member data exists in any further derived classes. This resolves the ambiguity of member names and data duplication. Virtual inheritance should only be used when necessary, as it introduces some overhead and can be more complex. In some situations, a programmer might intentionally want two distinct copies of a base class's data members in the final derived class.
π Definition β Virtual Inheritance: A C++ mechanism used in multiple inheritance to ensure that a common base class is shared, resulting in only one copy of its members in any further derived classes, thus solving the diamond problem.
π Formula (Syntax):
class IntermediateClass : public virtual BaseClass { ... };
class MostDerivedClass : public IntermediateClass1, public IntermediateClass2 { ... }; β Results in a single BaseClass subobject.
π Example: Using virtual inheritance to solve the diamond problem.
class Vehicle{
protected:
int weight;
};
class LandVehicle : public virtual Vehicle{ };
class WaterVehicle : public virtual Vehicle{ };
class AmphibiousVehicle: public LandVehicle, public WaterVehicle {
public:
AmphibiousVehicle(){
weight = 10; // No ambiguity: there is only one copy of weight from Vehicle
}
};
π‘ Why this matters: Virtual inheritance prevents the memory duplication and naming ambiguity inherent in the diamond problem. It creates a single, shared base class instance for the entire inheritance hierarchy.
β Key Takeaways
The most critical concepts from this lecture are that multiple inheritance allows a class to inherit from several base classes, but introduces the significant problem of name ambiguity when functions or data with the same name are inherited. You must use the scope resolution operator (ClassName::) to resolve these ambiguous calls. The diamond problem is a special case of ambiguity from multi-level multiple inheritance, creating two base class subobjects. The definitive solution to this is virtual inheritance, which guarantees a single shared copy of the base class, eliminating both memory redundancy and function ambiguity. Remember to use virtual inheritance only when a single common base is required; otherwise, multiple distinct copies can be intentional.
π§ Quick Revision Questions
- How do you declare a class
Cthat publicly inherits from classAand privately inherits from classB? - What compile-time error occurs when a derived class inherits two functions with the same name from different base classes, and how do you fix it?
- Explain what the "diamond problem" is in C++ and why it causes ambiguity.
- Write the
classdeclaration forWaterVehiclethat virtually inherits fromVehicle. - In the diamond problem scenario with virtual inheritance, how many copies of the topmost base class's data members exist in the most derived class's object?
π Lecture 32 β Generic Programming
π Overview: This lecture introduces the concept of generic programming in C++, which allows writing single functions or classes that work with multiple data types. It explains the motivation behind generic programming, introduces templates as the mechanism for implementation, and covers function templates with practical examples including user-defined specializations.
ποΈ Topics Covered
The lecture begins by demonstrating the problem of code duplication when creating functions and classes for different data types, then introduces generic programming as a solution. It covers the advantages of this approach, explains function templates and class templates, details template declaration syntax, discusses explicit type parameterization, and concludes with user-defined specializations for handling type-specific cases.
π Lecture Summary
32.1. Generic Programming
Generic programming refers to programs containing generic abstractions (general code that is same in logic for all data types like the printArray function), then we instantiate that generic program abstraction (function, class) for a particular data type. Such abstractions can work with many different types of data.
π‘ Why this matters: Instead of writing identical functions for int, char, double, float, short, and long arrays, generic programming lets us write one version that works for all.
Advantages of generic programming:
- Reusability: Code can work for all data types
- Writability: Code takes lesser time to write
- Maintainability: Code is easy to maintain as changes are needed to be made in a single function or class instead of many functions or classes
π Definition β Generic Programming: A programming technique where programs contain generic abstractions (general code) that can be instantiated for particular data types, allowing the same code to work with many different types of data.
π Example β The Problem: Three nearly identical printArray functions for int, char, and double arrays:
void printArray(int* array, int size) { /* loop printing */ }
void printArray(char* array, int size) { /* loop printing */ }
void printArray(double* array, int size) { /* loop printing */ }
All do the same functionality but on different data types β this is code duplication.
32.2. Templates
In C++, generic programming is done using templates. The compiler generates different type-specific copies from a single template. This concept is similar to making a prototype in the form of a class for all objects of the same kind.
Two kinds of templates:
- Function Templates: For writing general functions like
printArray - Class Templates: For writing general classes like the
Arrayclass
π Definition β Template: A C++ feature that enables generic programming by allowing the creation of functions and classes that can work with any data type. The compiler generates type-specific copies from a single template definition.
32.3. Function Templates
A function template can be parameterized to operate on different types of data types.
Declaration syntax:
template< class T >
void funName( T x );
// OR
template< typename T >
void funName( T x );
// OR
template< class T, class U, ... >
void funName( T x, U y, ... );
Note: T is a placeholder for the data type name. We use T instead of specific data types (like int, float, char) for which we want our function to work as a template. There is no difference between class T and typename T.
π Formula β Function Template Instantiation: template<typename T> void func(T param) β When called with an argument of type X, the compiler instantiates func(X param) automatically.
π Example β Function Template for printArray:
template< typename T >
void printArray( T* array, int size )
{
for ( int i = 0; i < size; i++ )
cout << array[ i ] << ", ";
}
Usage:
int main() {
int iArray[5] = { 1, 2, 3, 4, 5 };
printArray( iArray, 5 ); // Instantiated for int[]
char cArray[3] = { 'a', 'b', 'c' };
printArray( cArray, 3 ); // Instantiated for char[]
return 0;
}
Explicit Type Parameterization: When a function template does not have any parameter that uses the template type, we must explicitly specify the data type:
template <typename T>
T getInput() {
T x;
cin >> x;
return x;
}
int main() {
int x = getInput< int >(); // Explicitly instantiated for int
double y = getInput< double >(); // Explicitly instantiated for double
return 0;
}
Without explicit type parameterization, getInput() would cause a compilation error because the compiler cannot deduce the type from the function call alone.
π Definition β Explicit Type Parameterization: When instantiating a function template that doesn't have parameters of the template type, the data type must be explicitly specified in angle brackets after the function name, e.g., getInput< int >().
User-defined Specializations: A template compiler-generated code may not handle all types successfully. In that case, we can give explicit specializations for a particular data type(s).
π Example β The Problem with Specialization:
template< typename T >
bool isEqual( T x, T y ) {
return ( x == y );
}
This works correctly for int, double, and char:
isEqual(6,6)β returnstrueisEqual(6,7)β returnsfalseisEqual(6.6,6.6)β returnstrueisEqual('A','A')β returnstrue
But isEqual("abc","xyz") fails because it compares char* pointers (compares memory addresses, not string contents). Since char* comparison only checks if the first element matches, isEqual("abc","acc") incorrectly returns true because both point to strings starting with 'a'.
π Example β User-defined Specialization Solution:
template< typename T >
bool isEqual( T x, T y ) {
return ( x == y );
}
// Specialization for const char*
template< >
bool isEqual< const char* >( const char* x, const char* y ) {
return ( strcmp( x, y ) == 0 );
}
int main() {
cout << isEqual( 5, 6 ); // OK - uses generic template
cout << isEqual( 7.5, 7.5 ); // OK - uses generic template
cout << isEqual( "abc", "aba" ); // OK - uses specialization, returns false
return 0;
}
π Definition β User-defined Specialization: A specialized version of a function template for a specific data type that overrides the generic template behavior, used when the generic implementation would produce incorrect results for that particular type.
β Key Takeaways
Generic programming using templates is a powerful C++ feature that eliminates code duplication by allowing a single function or class to work with any data type. Function templates use either typename or class keywords to declare type parameters, and the compiler automatically generates appropriate type-specific code through template instantiation. When a function template lacks parameters of the template type (like getInput()), explicit type parameterization using angle brackets is required. User-defined specializations provide a mechanism to override the generic template behavior for specific data types when the default implementation would produce incorrect results, such as comparing C-style strings where pointer comparison fails. The three major benefits of this approach are reusability, improved writability, and easier maintainability since changes only need to be made in one place.
π§ Quick Revision Questions
- What are the two types of templates in C++ and what is each used for?
- Explain the difference between
template<typename T>andtemplate<class T>β is there any functional difference? - When would you need to use explicit type parameterization (e.g.,
getInput< int >()) instead of letting the compiler deduce the type? - Why does
isEqual("abc","xyz")fail with the generic template implementation, and how do user-defined specializations fix this? - List and explain the three major advantages of generic programming over writing separate functions for each data type.