π Lecture 18 β Self Assignment Problem and Other Binary Operators
π Overview: This lecture addresses the critical self-assignment problem in operator overloading, where assigning an object to itself can cause memory corruption. It then explores overloading compound assignment operators like
+=and demonstrates how to implement binary operators like+using non-member, non-friend functions to maintain encapsulation.
ποΈ Topics Covered
The lecture covers the self-assignment problem in copy assignment operators and its solution using a this pointer check. It discusses making the return type const to prevent assignment to sub-expressions, then moves to overloading the += operator for the Complex class. Finally, it examines friend functions versus non-member functions for operator overloading, showing three versions of the + operator for different operand combinations.
π Lecture Summary
18.1. Self assignment problem
When we assign a string object to itself, as done in the main function below, our program will produce unexpected results because the source and destination operands for copying are the same:
int main(){
String str1("Fakhir");
str1 = str1; // Self Assignment problem...
return 0;
}
The result of str1 = str1 leads to memory access violations or incorrect data copy because the program first deletes the buffer of the left-hand side operand, then attempts to copy from the right-hand side which has already been destroyed.
π Definition β Self Assignment Problem: When an object is assigned to itself, the assignment operator may destroy the object's resources (e.g., delete its buffer) before copying from the source, which is the same object, leading to undefined behavior.
We can resolve this issue by adding a simple if condition to ensure that both strings are not the same by comparing the this pointer to the address of the right-hand side operand:
String & String :: operator = (const String & rhs){
if(this != &rhs){
size = rhs.size;
delete [] bufferPtr; // deleting memory of left hand side operand
if(rhs.bufferPtr != NULL){
bufferPtr = new char[rhs.size+1];
strcpy(bufferPtr,rhs.bufferPtr);
// memory access violation or incorrect data copy
}
else bufferPtr = NULL;
}
return *this;
}
Now self-assignment is properly handled:
int main(){
String str1("Fakhir");
str1 = str1;
return 0;
}
We can make the return type const String & to avoid assignment to sub-expressions, such as (str1 = str2) = str3. However, as we can do that with primitive types, we may allow assignment to sub-expressions by keeping the return type as String & only.
π‘ Why this matters: The self-assignment check prevents a common bug where an object accidentally assigns to itself, which would corrupt memory. The choice of return type (const or non-const) affects whether chained assignments like (a=b)=c are allowed, matching primitive type behavior.
18.2. Other Binary operators
Overloading += operator:
class Complex{
double real, img;
public:
Complex & operator+=(const Complex & rhs);
Complex & operator+=(const double & rhs);
// ...
};
Complex & Complex::operator += (const Complex & rhs){
real = real + rhs.real;
img = img + rhs.img;
return * this;
}
Complex & Complex::operator += (const double & rhs){
real = real + rhs;
return * this;
}
int main(){
Complex c1, c2, c3;
c1 += c2;
c3 += 0.087;
return 0;
}
π Definition β Compound Assignment Operator: An operator like += that combines an operation with assignment, modifying the left-hand operand in place and returning a reference to it.
π Formula: c1 += c2 β c1.real = c1.real + c2.real; c1.img = c1.img + c2.img; β returns reference to c1
π Example: With Complex c1(3.0, 4.0) and c2(1.0, 2.0), after c1 += c2, c1.real = 4.0, c1.img = 6.0. With c3 += 0.087 and c3(2.0, 5.0), after operation, c3.real = 2.087, c3.img = 5.0.
18.3. Friend Functions and Operator overloading
Friend functions minimize encapsulation as we can access private data of any class using friend functions. This can result in:
- Data vulnerability
- Programming bugs
- Tough debugging
Hence, use of friend functions must be limited. We can overload operators without declaring them friend functions of a class. For example, the + operator can be defined as a non-member, non-friend function as shown below (three versions to handle three kinds of statements):
obj1 + obj2obj1 + 3.783.78 + obj1
Complex operator + (const Complex & a, const Complex & b){
Complex t = a; // creating temporary object t to store a+b
return t += b; // returning t by reference
}
Complex operator + (const double & a, const Complex & b){
Complex t = b;
return t += a;
}
Complex operator + (const Complex & a, const double & b){
Complex t = a;
return t += b;
}
π Definition β Non-member, Non-friend Function: A function that cannot access private members of a class but can still implement operators by using public member functions like operator+=.
π Example: For Complex c1(3.0, 4.0) and c2(1.0, 2.0), c1 + c2 calls operator+(c1, c2) which creates a temporary t = c1, then calls t += c2, returning the temporary. The result is Complex(4.0, 6.0).
π‘ Why this matters: Using non-friend functions preserves encapsulation and reduces bugs. The + operator is implemented in terms of +=, which is a common design pattern called "implementing in terms of" that reduces code duplication.
Other Binary operators
The operators -=, /=, *=, |=, %=, &=, ^=, <<=, >>=, != can be overloaded in a very similar fashion, following the same pattern of modifying *this and returning a reference.
β Key Takeaways
The most critical concepts from this lecture are: always check for self-assignment in copy assignment operators by comparing this to &rhs to prevent memory corruption; compound assignment operators like += should return a reference to *this to support chaining; operators can be overloaded as member functions, friend functions, or non-member non-friend functions, with non-friend being preferred to maintain encapsulation; binary operators like + are best implemented in terms of compound assignment operators (+=) to avoid code duplication; and the three versions of binary operators handle different operand type combinations (object+object, object+double, double+object).
π§ Quick Revision Questions
- What is the self-assignment problem, and how do you fix it in the copy assignment operator?
- Why would you make the return type of
operator=const, and what functionality does it prevent? - How does the
operator+=work for the Complex class, and what does it return? - What are three ways to overload operators in C++, and why are non-friend non-member functions preferred?
- How would you implement
operator+for the Complex class without using friend functions, and why does this approach preserve encapsulation?
π Lecture 19 β Overloading stream insertion extraction operators
π Overview: This lecture explains how to overload stream insertion (
<<) and extraction (>>) operators for user-defined classes in C++. It covers why these operators need special handling, the limitations of member function overloading, and the correct approach using friend functions to enable natural syntax and cascading.
ποΈ Topics Covered
The lecture begins with an introduction to stream insertion and extraction operators, explaining how cin and cout work with basic data types. It then demonstrates the problem when trying to use these operators with user-defined classes like Complex. The correct overloading technique using friend functions is presented for both insertion and extraction operators, followed by overloading comparison operators (equality and inequality) for the Complex class.
π Lecture Summary
19.1. Stream Insertion operator
Often we need to display data on the screen. C++ provides the insertion operator (<<) to put data on the output stream. The default output stream is the console, but it can also be a file or network socket.
π Example:
int i=1, j=2;
cout << "i= " << i << "\n";
cout << "j= " << j << "\n";
19.2. Stream Extraction operator
We also need to get data from the console, file, or network. This is achieved through the stream extraction operator (>>), which gets data from the input stream. The default input stream is from the console.
π Example:
int i,j;
cin >> i >> j; // getting value of i and j from user
Explanation:
cin and cout are objects of istream and ostream classes respectively. The insertion and extraction operators have been overloaded in istream and ostream classes for all basic types like int, float, long, double, and char*.
When we write cin >> i, the actual call passes objects to the overloaded function:
istream & operator >> (istream & in, int & i)
Here, cin is passed as istream object along with int i. The function returns an istream object by reference & to accommodate multiple input statements in a single line like cin >> i >> j.
Similarly for insertion operator:
ostream & operator << (ostream & os, const int & i)
If we try to use these operators for user-defined data types like our Complex class, the compiler will generate an error as it will not find any overloaded operator code for our Complex class:
Complex c1;
cout << c1; // Error
cout << c1 << 2; // Error cascaded statement
Compiler error: binary '<<' : no operator defined which takes a right-hand operand of type 'class Complex'
π‘ Why this matters: The same error will occur for the stream extraction operator, so we need to overload both operators (<< and >>) for our Complex class.
19.3. Overloading Stream Insertion Operator
First, we try to overload insertion << operator as a member function:
class Complex {
// ...
void operator << (const Complex & rhs);
};
When called as cout << c1;, this generates errors because it expects the left operand to be a Complex object, not ostream. The only working syntax would be c1 << cout;, which has two limitations:
- Difficult to understand and remember statement syntax (
c1 << cout ;) - Cascaded statements not possible (
cout << c1 << 2 ;)
The correct approach uses a friend function:
class Complex {
// ...
friend ostream & operator << (ostream & os, const Complex & c);
};
π Definition β Stream Insertion Operator Overloaded: ostream & operator << (ostream & os, const Complex & c)
The implementation:
// we want the output as: (real, img)
ostream & operator << (ostream & os, const Complex & c){
os << '(' << c.real
<< ','
<< c.img << ')';
return os;
}
Important: ostream reference cannot be const as it stores data in its buffer to insert on output stream. However, the Complex reference will be constant as we are only getting data from Complex object.
π Example:
Complex c1(1.01, 20.1), c2(0.01, 12.0);
cout << c1 << endl << c2;
Output:
( 1.01 , 20.1 )
( 0.01 , 12.0 )
Now cascading statements are also possible:
cout << c1 << c2;
is equivalent to:
operator<<( operator<<(cout,c1),c2);
Because the insertion operator is left to right associative, first the left part is executed, then the next part β as opposed to the copy assignment operator which is right associative.
19.4. Overloading Stream Extraction Operator
class Complex {
// ...
friend istream & operator >> (istream & i, Complex & c);
};
Important: istream cannot be const because the istream buffer will change as we get data from it. Similarly, Complex object cannot be const for stream extraction operator because we will add data to it and its state will change.
π Definition β Stream Extraction Operator Overloaded: istream & operator >> (istream & in, Complex & c)
Implementation:
istream & operator >> (istream & in, Complex & c){
in >> c.real;
in >> c.img;
return in;
}
π Example:
Complex c1(1.01, 20.1);
cin >> c1; // suppose we entered 1.0025 for c1.real and 0.0241 for c1.img
cout << c1;
Output:
( 1.0025 , 0.0241 )
19.5. Other Binary operators
Overloading comparison operators (Equality and Inequality operators)
class Complex {
public:
bool operator == (const Complex & c);
// friend bool operator == (const Complex & c1, const Complex & c2);
bool operator != (const Complex & c);
// friend bool operator != (const Complex & c1, const Complex & c2);
// ...
};
Equality operator as member function:
bool Complex::operator ==(const Complex & c){
if((real == c.real) && (img == c.img)){
return true;
}
else {
return false;
}
}
π Formula: (real == c.real) && (img == c.img) β returns true if both real and imaginary parts are equal
As non-member friend function:
bool operator ==(const Complex& lhs, const Complex& rhs){
if((lhs.real == rhs.real) && (lhs.img == rhs.img)){
return true;
}
else {
return false;
}
}
Inequality Operator:
bool Complex::operator !=(const Complex & c){
if((real != c.real) || (img != c.img)){
return true;
}
else {
return false;
}
}
π Formula: (real != c.real) || (img != c.img) β returns true if either real or imaginary parts differ
β Key Takeaways
The most critical point is that stream insertion and extraction operators cannot be overloaded as member functions for user-defined classes because the left operand must be an ostream or istream object, not the class object. They must be implemented as friend functions that take the stream object by reference and return it by reference to support cascading. For insertion (<<), the class object is passed as const reference since we only read from it, while for extraction (>>), it must be non-const since we modify it. The insertion operator is left-to-right associative, enabling natural cascading syntax like cout << c1 << c2. Finally, comparison operators like == and != can be overloaded either as member functions or non-member friend functions, comparing the real and imaginary parts component-wise.
π§ Quick Revision Questions
- Why can't stream insertion and extraction operators be overloaded as member functions of a user-defined class?
- What is the correct function signature for overloading the stream insertion operator, and why must the function return a reference?
- Explain why the Complex object is passed as
constin the insertion operator but as non-const in the extraction operator. - How does left-to-right associativity of the insertion operator enable cascaded statements like
cout << c1 << c2? - Write the implementation of both equality (
==) and inequality (!=) operators for the Complex class, comparing both real and imaginary parts.
π Lecture 20 β Modified String Class
π Overview: This lecture demonstrates how to extend a user-defined String class with operator overloading to provide intuitive and efficient string manipulation. It covers the subscript operator for character access, the function call operator for both character and substring operations, and the general principles of overloading unary operators.
ποΈ Topics Covered
The lecture begins by presenting a problem with the existing String class where changing a single character requires reallocating the entire buffer. It then presents solutions starting with a SetChar member function, followed by overloading the subscript operator [], the function call operator () for single character and substring operations, and finally an overview of overloading unary operators.
π Lecture Summary
Modified String Class
The existing String class has a SetString method that deletes and reallocates a new buffer whenever a string change is made, which is inefficient for large strings or single character changes.
π Definition β SetString: A member function that deletes the current buffer and allocates a new one when changing the entire string value.
π Example: Changing "Ping" to "Pong" with str2.SetString("Pong") involves deleting the entire "Ping" buffer and allocating a new buffer for "Pong" β too much overhead for a single character change.
To solve this, a SetChar function can be added:
void SetChar(char c, int pos){
if(bufferPtr != NULL){
if(pos>0 && pos<=size)
bufferPtr[pos] = c;
}
}
π Example: str1.SetChar('o', 2); changes "Ping" to "Pong" efficiently by modifying only the character at position 2.
20.1. Subscript [] Operator
An elegant solution is to overload the subscript operator [] to work like it does with built-in arrays, allowing both reading (r-value) and writing (l-value).
π Definition β Subscript operator []: An operator used for direct index-based access to elements of an array or collection.
π‘ Why this matters: Overloading [] allows our String class to behave like a built-in character array, making code more intuitive and readable.
π Example:
String str2;
str2.SetString("Ping");
str[2] = 'o'; // acting as l-value (writing)
cout << str[2]; // acting as r-value (reading)
20.2. Overloading Subscript [] Operator
The subscript operator must be overloaded as a member function with exactly one integer parameter.
class String{
// ...
public:
char & operator[](int);
// ...
};
char & String::operator[](int pos){
assert(pos>0 && pos<=size);
return stringPtr[pos-1];
}
π Formula: operator[](int pos) β returns a reference to char so it can be used on both left and right sides of assignment.
π Example:
String s1("Ping");
cout << s1.GetString() << endl; // Output: Ping
s1[2] = 'o'; // Changes 'i' to 'o'
cout << s1.GetString(); // Output: Pong
Output:
Ping
Pong
20.3. Overloading Function () operator
The function call operator () can also be overloaded. It must be a member function, can have any number of parameters, and any return type.
class String{
// ...
public:
char & operator()(int);
// ...
};
char & String::operator()(int pos){
assert(pos>0 && pos<=size);
return bufferPtr[pos-1];
}
π Definition β Function call operator (): An operator that can be overloaded to allow objects to be called like functions, with flexible parameter lists. π Example:
String s1("Ping");
char g = s1(2); // g = 'i' (reading)
s1(2) = 'o'; // writing
cout << g << "\n"; // Output: i
cout << s1.GetString(); // Output: Pong
Output:
i
Pong
20.4. Function Operator performing Sub String operation
The function call operator can be overloaded with two parameters to extract a substring.
class String{
// ...
public:
String operator()(int, int);
// ...
};
String String::operator()(int index, int subLength){
assert(index>0 && index+subLength-1<=size);
char * ptr = new char[subLength+1];
for (int i=0; i < subLength; ++i)
ptr[i] = bufferPtr[i+index-1];
ptr[subLength] = '\0';
String str(ptr);
delete [] ptr;
return str;
}
π Definition β Substring: A contiguous sequence of characters within a string, extracted starting from a given index for a specified length. π Example:
String s("Hello World");
cout << s(1, 5); // Extracts 5 characters starting from position 1
Output:
Hello
20.5. Unary Operators
Unary operators take one operand and act on the object with reference to which they are called.
π Definition β Unary operators: Operators that operate on a single operand, including: &, *, +, -, ++, --, !, ~
General syntax for unary operators:
- As Member Functions:
TYPE & operator OP ();β no argument needed, the object itself is the operand - As Non-member (Friend) Functions:
friend TYPE & operator OP (TYPE & t);β one argument (the object to be operated on)
Overloading unary - for Complex class:
class Complex{
// ...
Complex operator - (); // member function
// friend Complex operator -(Complex &); // alternative as friend
};
Complex Complex::operator -(){
Complex temp;
temp.real = -real;
temp.img = -img;
return temp;
}
Complex c1(1.0, 2.0), c2;
c2 = -c1;
// c2.real = -1.0
// c2.img = -2.0
π‘ Why this matters: Unary operator overloading allows user-defined types to use standard operators like -, ++, -- naturally, making code more intuitive and readable.
β Key Takeaways
Students must remember that the subscript operator [] must be overloaded as a member function with one integer parameter and returns a reference to allow both reading and writing. The function call operator () is versatile β it can be overloaded with any number of parameters for different purposes like character access or substring extraction. Unary operators follow a consistent pattern: as member functions they take no arguments, as non-member functions they take one argument. The assert function is used for bounds checking to ensure safe index access. Overloading these operators makes user-defined classes behave more like built-in types, improving code readability and efficiency.
π§ Quick Revision Questions
- Why is using
SetStringto change a single character in a large string inefficient, and what alternative is presented? - What is the return type of the overloaded subscript operator
[]in the String class, and why is this specific type necessary? - How does the function call operator
()differ from the subscript operator[]in terms of parameter flexibility? - In the substring operation using
operator(), what does the first parameter represent and what does the second parameter represent? - When overloading unary operators as member functions, how many parameters are required, and why?
π Lecture 21 β Unary Operators
π Overview: This lecture covers the overloading of unary operators, specifically pre and post increment/decrement operators for user-defined classes. It also introduces type conversion mechanisms in C++ including conversion constructors, explicit keyword, and type conversion operators, along with their drawbacks and best practices.
ποΈ Topics Covered
The lecture begins with explaining the behavior of ++ and -- operators for pre-defined types, distinguishing between post-increment and pre-increment semantics. It then demonstrates how to overload these operators as member and non-member functions for user-defined classes. The second major topic is type conversion, covering automatic conversion using single-parameter constructors, the explicit keyword to restrict implicit conversions, and conversion from current type to other types using operator overloading. Finally, it discusses drawbacks of type conversion operators and recommends using separate member functions instead.
π Lecture Summary
21.1. Behavior of ++ and -- for pre-defined types
Post-increment operator ++ increments the current value and then returns the previous value. Post-decrement -- works exactly like post-increment.
π Example:
int x = 1, y = 2;
cout << y++ << endl; // Output: 2
cout << y; // Output: 3
Post-increment cannot be chained or used as lvalue: y++++; and y++ = x; produce errors.
Pre-increment operator ++ increments the current value and then returns its reference. Pre-decrement works exactly like pre-increment.
π Example:
int y = 2;
cout << ++y << endl; // Output: 3
cout << y << endl; // Output: 3
Pre-increment can be chained and used as lvalue:
int x = 2, y = 2;
++++y; // y becomes 4
cout << y; // Output: 4
++y = x; // y becomes 2
cout << y; // Output: 2
For user-defined classes, pre-increment is overloaded as:
π Definition β Pre-increment operator: Returns a reference so the object can be used as an lvalue.
π Member function syntax: Complex & operator ++ ();
π Non-member function syntax: friend Complex & operator ++(Complex &);
π Example (Member function implementation):
Complex & Complex::operator++(){
real = real + 1;
return *this;
}
π Example (Non-member function implementation):
Complex & operator ++ (Complex & h){
h.real += 1;
return h;
}
π‘ Why this matters: Returning a reference allows chaining and using the result as lvalue, e.g., ++h1 = h2 + ++h3; is valid.
21.2. Post-increment operator
A post-fix unary operator is implemented using a member function with 1 dummy int argument OR a non-member function with two arguments. The dummy parameter tells the compiler it is post-increment.
In post-increment, current value of the object is stored in a temporary variable, current object is incremented, then value of the temporary variable is returned.
π Member function syntax: Complex operator ++ (int);
π Non-member function syntax: friend Complex operator ++(const Complex &, int);
π Example (Member function):
Complex Complex::operator ++ (int){
complex t = *this;
real += 1;
return t;
}
π Example (Non-member function):
Complex operator ++ (const Complex & h, int){
complex t = h;
h.real += 1;
return t;
}
Post-increment cannot be used as lvalue: h3++ = h2 + h3++; produces an error.
The pre and post decrement operator -- is implemented in exactly the same way.
21.3. Type Conversion
The compiler automatically performs a type coercion of compatible types:
int f = 0.021; // float automatically converted to int, compiler issues warning
double g = 34; // int automatically converted to double
The user can also explicitly convert between types using casting:
int g = (int)0.0210; // C-style cast
double h = double(35); // function-style cast
For user-defined classes, there are two types of conversions:
- From any other type to current type: Requires a constructor with a single parameter
- From current type to any other type: Requires an overloaded operator
Conversion from other type to current type (int to String):
π Example:
class String{
public:
String(int a);
char * GetStringPtr() const;
};
String::String(int a){
cout << "String(int) called..." << endl;
char array[15];
itoa(a, array, 10);
size = strlen(array);
bufferPtr = new char [size + 1];
strcpy(bufferPtr, array);
}
int main(){
String s = 345; // implicit conversion using constructor
cout << s.GetStringPtr() << endl; // Output: 345
return 0;
}
π Keyword explicit: Restricts automatic conversions. Only works with constructors. When used, casting must be explicitly performed by the user.
π Example:
class String{
public:
explicit String(int); // prevents implicit conversion
};
int main(){
String s;
s = 'A'; // Error: implicit conversion not allowed
s1 = String(101); // valid: explicit casting
s2 = (String)204; // valid: explicit casting
return 0;
}
π‘ Why this matters: Without explicit, a character like 'A' (ASCII 65) could be unintentionally converted to integer 65 and then to a String, when the user actually wanted String "A".
Type Conversion Operator β Used for converting from current type (user defined) to any other basic type or user defined type.
π General Syntax: TYPE1::operator TYPE2();
Example: String::operator char *(); converts String object to char*.
These functions are written as member functions with NO return type and NO arguments specified. Return type is implicitly taken to be TYPE2 by compiler.
π Example:
class String{
public:
operator int();
operator char *();
};
String::operator int(){
if(size > 0)
return atoi(bufferPtr);
else
return -1;
}
String::operator char *(){
return bufferPtr;
}
int main(){
String s("2324");
cout << (int)s << endl << (char *)s; // Output: 2324 \n 2324
return 0;
}
21.4. User Defined types
User-defined types can be converted in exactly the same way. Only prototype is shown:
class String{
operator Complex();
operator HugeInt();
operator IntVector();
};
21.5. Drawbacks of Type Conversion Operator
β Problem: Type conversion operators can cause unexpected implicit conversions.
π Example:
class String{
public:
String(char *);
operator int();
};
int main(){
String s("Fakhir");
cout << s; // << is NOT overloaded for String
// compiler automatically converts s to int
// Output: Junk Returned...
return 0;
}
β Solution: DO NOT use type conversion operators. Instead, use separate member functions for such type conversions.
π Example (Recommended approach):
class String{
public:
String(char *);
int AsInt(); // separate member function instead of operator
};
int String::AsInt(){
if(size > 0)
return atoi(bufferPtr);
else
return -1;
}
int main(){
String s("434");
cout << s; // error: no matching operator
cout << s.AsInt(); // works correctly
return 0;
}
β Key Takeaways
The most critical concepts from this lecture are: pre-increment returns a reference to the object and can be used as lvalue, while post-increment returns a temporary value and cannot. The dummy int parameter in the operator function tells the compiler whether it's post-increment. For type conversion, constructors with single parameters allow conversion from other types to the current type, but the explicit keyword should be used to prevent unintended implicit conversions. Type conversion operators (like operator int()) allow conversion from current type to other types but are dangerous because the compiler may apply them unexpectedly. The recommended practice is to use explicit constructors and separate member functions (like AsInt() or GetStringPtr()) instead of type conversion operators to avoid subtle bugs.
π§ Quick Revision Questions
- What is the difference between pre-increment and post-increment in terms of what they return?
- Why can post-increment not be used as an lvalue (e.g.,
h3++ = h2 + h3++;is an error)? - How does the compiler distinguish between pre-increment and post-increment operator overloads?
- What is the purpose of the
explicitkeyword and what types of constructors does it work with? - Why is it recommended to use separate member functions like
AsInt()instead of type conversion operators likeoperator int()?
π Lecture 22 β Practical Implementation of Inheritance in C++
π Overview: This lecture covers the practical implementation of inheritance in C++ programming. It explains how classes inherit characteristics from base classes, the UML notation for inheritance, types of inheritance in C++, the βIS Aβ relationship, member access, memory allocation, and the order of execution for constructors and destructors. Understanding these concepts is crucial for designing reusable and hierarchical class structures in object-oriented programming.
ποΈ Topics Covered
Inheritance in classes, UML notation of inheritance, types of inheritance in C++, βIS Aβ relationship, accessing members in inheritance, allocation of derived class objects in memory, constructors and their execution order, base class initializers, initializing members of derived classes, destructors and their order of execution, and practical C++ examples demonstrating inheritance.
π Lecture Summary
22.2. Inheritance in Classes
If a class B inherits from class A, then B contains all the characteristics (information structure and behavior) of class A. The class whose behavior is being inherited is called base class (or parent class), and the class that inherits the behavior is called derived class (or child class). Besides inherited characteristics, a derived class may have its own unique characteristics.
22.3. UML Notation
Inheritance is represented in UML by an arrow from the derived class to the parent class. The arrow points toward the parent class.
π Definition β Inheritance Notation: UML uses an open arrow from child to parent to show βIS Aβ relationship.
22.4. Inheritance in C++
In C++, we can inherit a class from another class in three ways:
- Public β Public and protected members of base class retain their access levels in derived class.
- Private β Public and protected members of base class become private in derived class.
- Protected β Public and protected members of base class become protected in derived class.
π Definition β Access Specifiers: Determines how members of the base class are accessible in the derived class.
22.5. βIS Aβ Relationship
Inheritance represents an βIS Aβ relationship. For example, βa student IS A person.β In general, inheritance means βderived class IS A kind of parent class.β
C++ Syntax of Inheritance:
class ChildClass : public BaseClass {
// ...
};
Example:
class Person {
// ...
};
class Student : public Person {
// ...
};
Accessing Members
- Public members of the base class become public members of the derived class.
- Private members of the base class are not accessible from outside the base class, even in the derived class β this is information hiding.
Example:
class Person {
char *name;
int age;
public:
const char *GetName() const;
int GetAge() const;
};
class Student : public Person {
int semester;
int rollNo;
public:
int GetSemester() const;
int GetRollNo() const;
void Print() const;
};
class Teacher : public Person {
char *dept;
int course;
public:
char *GetDept() const;
int GetCourse() const;
void Print() const;
};
Error in Code:
void Student::Print() {
cout << name << β is inβ << β semester β << semester; // Error: 'name' is private in Person
}
Corrected Code:
void Student::Print() {
cout << GetName() << β is in semester β << semester; // Use public GetName() instead
}
main function:
int main(){
Student stdt;
stdt.semester = 0; // error: private member
stdt.name = NULL; // error: private member in base class
cout << stdt.GetSemester(); // OK
cout << stdt.GetName(); // OK
return 0;
}
π Definition β char data type handling in C++:* char arrays (char[]) can be handled statically (e.g., char name[30];) or dynamically (e.g., char *name; name = new char[30];).
Allocation in Memory
The object of a derived class is represented in memory as containing an anonymous object of the base class followed by the derived class's own data members.
Derived Class Object
|----------------------|
| base member1 |
| base member2 |
| ... | <-- Anonymous base class object
|----------------------|
| derived member1 |
| derived member2 |
| ... | <-- Derived class's own data members
|----------------------|
π Memory Layout Rule: Every derived class object has an anonymous base class object embedded within it. Base class members are stored first, then derived class members.
Constructors
- The anonymous object of the base class must be initialized using the constructor of the base class.
- When a derived class object is created, the constructor of the base class is executed before the constructor of the derived class.
Example:
class Parent {
public:
Parent(){ cout << βParent Constructor...β; }
};
class Child : public Parent {
public:
Child(){ cout << βChild Constructor...β; }
};
int main(){
Child cobj;
return 0;
}
Output:
Parent Constructor...
Child Constructor...
Constructor Rules when No Default Constructor Exists
- If the default constructor of the base class does not exist, the compiler will try to generate a default constructor for the base class and execute it before the derived class constructor.
- If the user has provided only an overloaded constructor for the base class, the compiler will not generate a default constructor for the base class.
Example (Error):
class Parent {
public:
Parent(int i){} // Only non-default constructor exists
};
class Child : public Parent {
public:
Child(){} // ERROR: No default constructor for Parent to call
} Child_Object;
π Definition β Default Constructor: A constructor that has either no parameters or all parameters with default values. It can be used to create an object without passing any arguments.
π Definition β Implicit Default Constructor: The compiler generates this if no constructor is provided for the class.
π Definition β Explicit Default Constructor: A user-defined constructor with no arguments or all arguments having default values.
Solution: Call the base class non-default constructor explicitly using the base class initializer in the derived class constructor's initializer list.
Base Class Initializer
C++ provides a mechanism to explicitly call a constructor of the base class from the derived class. The syntax is similar to member initializer lists and is called base-class initialization.
Example:
class Parent {
public:
Parent(int i){/*...*/};
};
class Child : public Parent {
public:
Child(int i): Parent(i) { /*...*/ } // Base class initializer
};
Another example:
class Parent {
public:
Parent(){ cout << βParent Constructor...β; }
};
class Child : public Parent {
public:
Child(): Parent() { cout << βChild Constructor...β; }
};
Base Class Initializer with Member Initializer
User can provide base class initializer and member initializer simultaneously.
Example:
class Parent {
public:
Parent(){/*...*/}
};
class Child : public Parent {
int member;
public:
Child(): member(0), Parent() { /*...*/ }
};
Key Rule: The base class constructor is executed before the initialization of data members of the derived class, even if the base class initializer is written after the member initializer.
Initializing Members
- A derived class can only initialize members of the base class using overloaded constructors (via base class initializer).
- A derived class cannot initialize public data members of the base class using member initialization list.
Example (Error):
class Person {
public:
int age;
char *name;
Person();
};
class Student: public Person {
private:
int semester;
public:
Student(int a): age(a) { // error: cannot initialize base class member via member initializer
}
};
Reason: It would be an assignment, not an initialization, and base class members must be initialized by the base class constructor.
Destructors
- Destructors are called in reverse order of constructors.
- The derived class destructor is called before the base class destructor.
Example:
class Parent {
public:
Parent(){ cout << βParent Constructorβ; }
~Parent(){ cout << βParent Destructorβ; }
};
class Child : public Parent {
public:
Child(){ cout << βChild Constructorβ; }
~Child(){ cout << βChild Destructorβ; }
};
Output:
Parent Constructor
Child Constructor
Child Destructor
Parent Destructor
β Key Takeaways
- Inheritance allows a derived class to reuse base class members, but private members of the base class are never accessible in the derived class β only public/protected members are accessible (depending on inheritance type). This enforces information hiding.
- Memory layout of a derived class object contains an anonymous base class object first, then derived class members. Constructors execute base first, then derived; destructors execute in reverse order (derived first, then base).
- If a base class has no default constructor, the derived class must explicitly call a base class constructor using the base class initializer syntax in its constructorβs initializer list (e.g.,
Child(int i): Parent(i) {...}). - A derived class cannot initialize base class data members directly using member initialization lists β it must rely on the base class constructor.
- The βIS Aβ relationship is fundamental: inheritance models that a derived class is a specialized version of the base class (e.g.,
Studentis aPerson).
π§ Quick Revision Questions
- What is the difference between public, private, and protected inheritance in C++, and how does each affect access to base class members?
- Draw the memory layout of a derived class object. Which part gets constructed first: base class members or derived class members?
- Why does the code
Student(int a): age(a) { }cause an error? How would you correctly initialize theagemember inherited fromPerson? - What order are constructors and destructors executed when a derived class object is created and destroyed? Give the output for a base class βParentβ and derived class βChildβ with print statements in each.
- How do you explicitly call a non-default base class constructor from a derived class? Write the syntax using a base class initializer.