π Lecture 12 β Review (Static Data Members and More)
π Overview: This lecture reviews the concept of static data members in C++, including their definition, memory allocation, initialization, and access patterns. It also covers static member functions, the
thispointer's relationship with static members, and introduces arrays of objects, which are foundational for managing multiple class instances efficiently.
ποΈ Topics Covered
The lecture covers the definition and syntax of static data members, their allocation and initialization at file scope, two ways to access them (dot operator vs. scope resolution), their lifetime independent of objects, practical uses like counting objects, the problem of public accessibility leading to static member functions, restrictions on static functions (no access to non-static members, no this pointer), comparison with global variables, and finally the rules for creating arrays of objects (requiring a default constructor or explicit initialization).
π Lecture Summary
Review: Static Data Member
A static data member is defined as "a variable that is part of a class, yet is not part of an object of that class." Static data members are shared by all instances of a class and do not belong to any particular instance.
Memory for static variables is allocated in class space, whereas for instance variables, memory is separate for each object. For example, with class Student containing static int noOfStudents;, creating objects s1, s2, s3 results in noOfStudents residing once in the class space, while instance-specific data like rollNo is stored separately per object.
Static Data Member (Syntax): The keyword static is used to declare a static data member inside the class:
class ClassName{
...
static DataType VariableName;
};
Defining Static Data Member (allocating memory): The static data member is declared inside the class but must be defined outside the class:
DataType ClassName::VariableName;
Initializing Static Data Member: Static data members should be initialized once at file scope, at the time of definition:
int Student::noOfStudents = 0;
Note: A private static member cannot be accessed outside the class except for this initialization.
If static data members are not explicitly initialized at definition, they are automatically initialized to 0:
int Student::noOfStudents; // equivalent to int Student::noOfStudents = 0;
π Definition β Static Data Member: A class variable shared by all objects of that class, declared with the static keyword, defined outside the class, and initialized once at file scope (defaults to 0).
12.1. Accessing Static Data Member
There are two ways to access a static data member:
- Access like a normal data member (using the dot operator
.) - Access using the scope resolution operator
::
Example:
class Student{
public:
static int noOfStudents;
};
int Student::noOfStudents;
int main(){
Student aStudent;
aStudent.noOfStudents = 1; // via dot operator
Student::noOfStudents = 1; // via scope resolution
return 0;
}
12.2. Life of Static Data Member
- Static data members are created even when there is no object of a class.
- They remain in memory even when all objects of a class are destroyed.
Example (alive without objects):
class Student{
public:
static int noOfStudents;
};
int Student::noOfStudents;
int main(){
Student::noOfStudents = 1; // Works even with no objects created
}
Example (persist after objects destroyed):
class Student{
public:
static int noOfStudents;
};
int Student::noOfStudents;
int main(){
{
Student aStudent;
aStudent.noOfStudents = 1;
} // aStudent destroyed here, but...
Student::noOfStudents = 1; // static member still accessible
return 0;
}
Uses: They can store information required by all objects, like global variables but scoped to the class.
Practical Example β Counting Objects:
class Student{
...
public:
static int noOfStudents;
Student();
~Student();
...
};
int Student::noOfStudents = 0;
Student::Student(){
noOfStudents++;
}
Student::~Student(){
noOfStudents--;
}
int main(){
cout << Student::noOfStudents << endl; // Output: 0
Student studentA;
cout << Student::noOfStudents << endl; // Output: 1
Student studentB;
cout << Student::noOfStudents << endl; // Output: 2
return 0;
}
Problem: In this example, noOfStudents is accessible outside the class, which is a bad design because the local data member is kept public.
π‘ Why this matters: Encapsulation is violated when static data members are public. The solution is to make them private and provide static member functions for controlled access.
12.3. Static Member Function
Definition: "The function that needs access to the members of a class, yet does not need to be invoked by a particular object, is called static member function."
- They are used to access static data members.
- Access mechanism for static member functions is the same as for static data members (via class name and
::or via a specific object). - They cannot access any non-static members.
Example:
class Student{
static int noOfStudents;
int rollNo;
public:
static int getTotalStudent(){
return noOfStudents;
}
};
int main(){
int i = Student::getTotalStudents(); // OK β accesses static member
return 0;
}
Error Example β Accessing non-static member from static function:
int Student::getTotalStudents(){
return rollNo; // Error: There is no instance of Student, rollNo cannot be accessed
}
π Definition β Static Member Function: A class-level function declared with static that can only access static data members and other static member functions, called without an object instance.
12.4. this Pointer and Static Member Functions
- The
thispointer is passed implicitly to non-static member functions. - The
thispointer is NOT passed to static member functions. - Reason: Static member functions cannot access non-static data members, so there is no need for a pointer to a specific object.
12.5. Global Variable vs. Static Members
- An alternative to static member is to use a global variable.
- Global variables are accessible to all entities of the program.
- Use of global variables is against the principle of information hiding.
π‘ Why this matters: Static members provide the benefits of global data (shared state) while maintaining encapsulation within the class, unlike global variables.
12.6. Array of Objects
- An array of objects can only be created if an object can be created without supplying an explicit initializer.
- There must always be a default constructor if we want to create an array of objects (unless explicitly initialized).
Example β OK (default constructor exists):
class Test{
public:
};
int main(){
Test array[2]; // OK β compiler provides default constructor
return 0;
}
Example β OK (explicit default constructor):
class Test{
public:
Test();
};
int main(){
Test array[2]; // OK
return 0;
}
Example β Error (no default constructor):
class Test{
public:
Test(int i);
};
int main(){
Test array[2]; // Error β no default constructor
return 0;
}
Solution with explicit initialization:
class Test{
public:
Test(int i);
};
int main(){
Test array[2] = {Test(0), Test(0)}; // OK β explicitly initialized
return 0;
}
Alternative with named objects:
class Test{
public:
Test(int i);
};
int main(){
Test a(1), b(2);
Test array[2] = {a, b}; // OK β copy initialization
return 0;
}
π Key Rule: To create an array of objects, either provide a default constructor or initialize each array element explicitly.
β Key Takeaways
Static data members are class-level variables shared across all objects, stored in class space, and persist even when no objects exist. They must be declared inside the class with static and defined outside using scope resolution, defaulting to zero if not explicitly initialized. Static member functions provide controlled access to these members but cannot access non-static data or use the this pointer. Arrays of objects require a default constructor or explicit initialization for each element; without one, compilation fails. These concepts are fundamental for managing shared state and object collections in object-oriented design.
π§ Quick Revision Questions
- What is the difference in memory allocation between a static data member and an instance data member?
- How do you properly declare, define, and initialize a private static data member in C++?
- Why can't a static member function access a non-static data member like
rollNo? - What happens to a static data member when all objects of its class are destroyed?
- What must be true about a class to create an array of its objects, and what is the alternative if that condition is not met?
π Lecture 13 β Pointer to Objects and Date Class
π Overview: This lecture covers pointer to objects, dynamic allocation of objects using the
newoperator, and a comprehensive case study on designing aDateclass. It demonstrates how to combine pointer concepts, static members, and proper class design in a practical application.
ποΈ Topics Covered
Pointer to objects and their similarity to pointers to built-in types, using new operator for dynamic object allocation, breakup of new operation into memory allocation and constructor calling, and a complete case study designing a Date class with static default date, getters/setters, and date manipulation functions including leap year validation.
π Lecture Summary
13.1. Pointer to Objects
Pointers to objects work similarly to pointers to built-in types. They store the memory address of an object and can be used to access object members using the arrow operator (->). The new operator can be used to dynamically allocate objects at runtime.
π Definition β Pointer to object: A variable that stores the memory address of an object, allowing indirect access to the object's members.
π Example 1: Basic pointer to object
Student obj;
Student *ptr;
ptr = &obj;
ptr->setRollNo(10);
π Example 2: Dynamic allocation with new
Student *ptr;
ptr = new Student; // allocates memory and calls default constructor
ptr->setRollNo(10);
π Example 3: Dynamic allocation with parameterized constructor
Student *ptr;
ptr = new Student("Ali"); // calls constructor with argument
ptr->setRollNo(10);
π Example 4: Dynamic array of objects
Student *ptr = new Student[100]; // allocates array of 100 Student objects
for(int i = 0; i < 100; i++) {
ptr->setRollNo(10);
}
13.2. Breakup of new Operation
The new operator is decomposed into two steps:
- Allocating space in memory for the object
- Calling the appropriate constructor to initialize the object
13.3. Case Study: Date Class Design
Design a class Date that allows users to:
- Get and set current day, month, and year
- Increment by x number of days, months, and years
- Set default date
Attributes:
day(int)month(int)year(int)defaultDate(static Date) β shared by all objects
class Date {
int day;
int month;
int year;
static Date defaultDate; // static member shared by all instances
...
};
Interfaces:
getDay,getMonth,getYearsetDay,setMonth,setYearaddDay,addMonth,addYearsetDefaultDateβ must be static since it modifies the static member
Constructors and Destructors:
Date(int aDay = 0, int aMonth = 0, int aYear = 0);
~Date(); // Destructor
Implementation of Date Class
Static member initialization:
The static member variable defaultDate must be initialized outside the class definition.
Date Date::defaultDate(07, 3, 2005); // initializes static default date
Constructor implementation:
If any parameter is 0, it uses the corresponding value from defaultDate.
Date::Date(int aDay, int aMonth, int aYear) {
if(aDay == 0) {
this->day = defaultDate.day; // use default date's day
} else {
setDay(aDay);
}
// similarly for month and year
}
Destructor: No housekeeping required in this case.
Date::~Date() { }
Getter and Setter examples:
void Date::setMonth(int a) {
if(a > 0 && a <= 12) {
month = a;
}
}
int Date::getMonth() const {
return month;
}
addYear method: When adding years, if the date is Feb 29 and the new year is not a leap year, adjust to March 1.
void Date::addYear(int x) {
year += x;
if(day == 29 && month == 2 && !leapYear(year)) {
day = 1;
month = 3; // adjust to March 1
}
}
Helper function β leapYear:
bool Date::leapYear(int x) const {
if((x % 4 == 0 && x % 100 != 0) || (x % 400 == 0)) {
return true;
}
return false;
}
π‘ Why this matters: A year is a leap year if divisible by 4 but not by 100, OR divisible by 400.
setDefaultDate:
void Date::setDefaultDate(int d, int m, int y) {
if(d >= 0 && d <= 31) {
day = d;
}
// ... similar validation for month and year
}
13.4. Complete Code of Date Class
The complete implementation includes:
- Private data members:
day,month,year, and staticdefaultDate - Public setters/getters for all attributes
addDay,addMonth,addYearmethodssetDefaultDatestatic methodsetDatemethod that sets all three values at once- Constructor with default parameters using 0 to trigger default date usage
- Destructor that prints "Date destructor"
int main() {
Date aDate(0, 0, 0); // uses default date values
aDate.setDate(20, 10, 2011);
system("pause");
}
β Key Takeaways
Pointers to objects work exactly like pointers to built-in types, using the arrow operator -> for member access. The new operator performs two operations: memory allocation and constructor calling. The Date class case study demonstrates how to design a class with static members shared across all instances, proper validation in setters, and the special handling of February 29 when adding years to avoid invalid dates. Static members must be initialized outside the class definition. Constructor parameters set to 0 can trigger the use of default date values, providing flexibility in object creation.
π§ Quick Revision Questions
- What two operations does the
newoperator perform when creating an object? - Why must the
setDefaultDatemethod be declared asstaticin the Date class? - How does the
addYearmethod handle the case where the current date is February 29 and the new year is not a leap year? - What is the correct way to initialize a static data member of a class?
- In the Date constructor, what happens if a parameter value is 0?
π Lecture 14 β Composition
π Overview: This lecture introduces the concept of composition in object-oriented programming, where one class contains objects of another class as members, establishing a "has-a" relationship. It demonstrates how composition simplifies code by reusing existing classes, using the example of a
Studentclass that now contains aStringobject instead of managing raw character pointers directly. The lecture also covers the order of constructor and destructor calls in composed objects.
ποΈ Topics Covered
The lecture covers the definition and concept of composition as a "part-whole" relationship, the implementation details of a String class used for composition, the revised Student class that incorporates this String object, how to access methods of composed objects, and the important sequence of constructor and destructor calls between composing and composed objects.
π Lecture Summary
14.1. Composition
Composition is a concept where one object is part of another object, establishing a relationship of part and whole. In this relationship, the lifetime of one object depends upon the other, and the part objects are essential components of the whole. For example, a person is composed of hands, eyes, and feet.
The lecture starts with the original Student class implementation from previous lectures that managed a char * name pointer with dynamic memory allocation. The class had private members float gpa, char * name, and int rollNumber, with constructors handling deep copying for the name string.
The instructor introduces composition by stating that in C++, "it is all about code reuse." Composition is defined as creating objects of one class inside another class, representing a "Has a" relationship β for example, "Bird has a beak" or "Student has a name."
The code is modified to replace the char * name with a String object, as it qualifies to be an object because many operations need to be applied to it, such as dynamic creation and deletion, string copy using deep copy, and searching a substring.
String Class Implementation
The String class is presented to show how it simplifies the original Student object and how composition is used.
class String{
private:
char * ptr;
public:
String(); // default constructor
String(const String &); // copy constructor
void SetString(const char *); // setter function
const char * GetString() const; // getter function returning const pointer
~String()
...
};
The String class has a private data member char * ptr. Its default constructor initializes ptr to NULL. The copy constructor performs deep copying by checking if the source's ptr is not NULL, then allocating new memory and copying the string.
The SetString function handles two important issues:
- Memory leakage: If we simply set the pointer, memory will be outside of our object and may cause problems later.
- The user still has a pointer to the passed value and can modify it.
These issues are resolved by allocating new memory and deleting previous memory in SetString. The function checks if ptr is not NULL, deletes it, and sets it to NULL. Then, if the input string is not NULL, it allocates new memory and copies the string.
The GetString function returns ptr as a const char *, ensuring the private data member cannot be modified through the returned pointer.
The destructor deletes the dynamically allocated memory for ptr and displays a message. The instructor notes that any time dynamic memory is deleted, the pointer should also be set to NULL.
Revised Student Class with Composition
The Student class is now rewritten to include a composed String object instead of managing raw character pointers.
class Student{
private:
float gpa;
int rollNumber;
String name;
public:
Student(char* =NULL, int=0, float=0.0);
Student(const Student &);
void SetName(const char *);
String GetName() const;
const char * GetNamePtr() const;
~Student();
...
};
The constructor uses name.SetString(_name) to set the composed object's value. The copy constructor uses a single line: name.SetString(s.name.GetString()); which is explained step by step:
name.SetString(...)β setting composed name of newly created objects.name.GetString()β accessing the composed object string name of object to be copieds.name.GetString()β accessing the value of composed object string name by calling its member functionGetString- Overall result: the value of composed object string of object to be copied will be copied to newly created object's composed object string
The GetNamePtr function returns name.GetString(), and SetName calls name.SetString(n). The destructor simply displays a message; it does not need to manually delete memory because the String destructor handles that automatically.
Important Points about Composition
- Methods of composed objects can be accessed in the same way as methods of other objects, using the syntax:
Name of composed object.MemberFunction - Member functions of a class can access its private data members. For example, in the copy constructor,
gpa = s.gpaandrollNo = s.rollNodirectly access private members of thesobject because the code is within aStudentmember function.
Constructors & Composition
Constructors of the sub-objects are always executed before the constructors of the master class. The output from the example program demonstrates this order:
Constructor::String..
Constructor::Student..
Name: Fakhir
Destructor::Student..
Destructor::String..
π Definition β Composition: A relationship where one object is part of another object, and the lifetime of one depends on the other. The part objects are essential components of the whole.
π‘ Why this matters: Understanding composition allows you to build complex objects from simpler, reusable components, promoting code reuse and simplifying memory management.
π Example: The Student class contains a String name object. When a Student is created, first the String constructor runs (creating the name part), then the Student constructor runs (creating the whole). When a Student is destroyed, the Student destructor runs first, then the String destructor runs.
Constructor calling order: Constructors are called from composed objects to composing objects (String first, then Student).
Destructor calling order: Destructors are called from composing objects to composed objects (Student first, then String).
β Key Takeaways
Composition establishes a "has-a" relationship where one class contains objects of other classes as members, with the composed object's lifetime depending on the composing object. Constructors are called bottom-up (composed first, composing second), while destructors are called top-down (composing first, composed second). Using composition simplifies code by delegating memory management and operations to the composed class, eliminating the need for the containing class to manage raw pointers and dynamic memory directly. When accessing private data members of composed objects within the containing class's member functions, the dot operator is used to call the composed object's public methods. The GetString function should return a const char * to prevent modification of private data through the returned pointer.
π§ Quick Revision Questions
- What is composition and what type of relationship does it represent between classes?
- In what order are constructors called for the composing object and the composed object?
- In what order are destructors called for the composing object and the composed object?
- Why does the
Stringclass'sGetStringfunction return aconst char *instead of justchar *? - What two problems does the
SetStringfunction solve by allocating new memory instead of simply assigning the pointer?
π Lecture 15 β Composition
π Overview: This lecture explores the concepts of composition and aggregation, detailing how objects relate to one another. It introduces the use of member initialization lists to efficiently construct embedded objects. The lecture also covers friend functions and friend classes, which grant non-member functions and other classes access to private data.
ποΈ Topics Covered
The lecture begins by reviewing the composition example from the previous session, focusing on the Student and String classes. It then demonstrates how to initialize embedded objects using a member initialization list instead of explicit setter methods, leading to an overloaded constructor for the String class. The concept is extended by adding a Date object to the Student class, further illustrating composition. Next, the lecture distinguishes composition from aggregation, providing real-world examples like student-teacher and room-chair relationships and showing the C++ implementation of aggregation using pointers. Finally, it introduces friend functions and friend classes, explaining their necessity, how they are declared, and their implications for encapsulation.
π Lecture Summary
Composition
The lecture revisits the concept of composition with the Student and String classes. In the previous approach, the Student constructor was forced to call name.SetString(n) to initialize its String sub-object because the String class lacked a parameterized constructor. This is an inefficient overhead.
π Overloaded Constructor β String(char *): A new constructor for the String class that takes a character pointer and initializes the object's internal string data.
String::String(char * str){
if(str != NULL){
ptr = new char[strlen(str)+1];
strcpy(ptr, str);
}
else ptr = NULL;
cout << "Overloaded Constructor::String..\n";
}
π Member Initialization List: A special syntax used in constructor definitions to directly initialize data members and base classes before the constructor body executes.
π Formula: Student::Student(char * n, int roll, float g): name(n) { ... } β The Student constructor uses the member initialization list to call the String(char*) constructor for the name object.
π Example:
int main(){
Student aStudent("Fakhir", 899, 3.1); // Calls String(char*) for name
return 0;
}
Output:
Overloaded Constructor::String..
Constructor::Student..
Destructor::Student..
Destructor::String..
π‘ Why this matters: The member initialization list directly initializes sub-objects, avoiding the need for an explicit setter call within the constructor body. This is more efficient and is the correct way to initialize const members and base classes.
The lecture extends the example by adding a Date member to the Student class.
π Example: Student with Date:
Student
- name: String
- birthDate: Date
Student::Student(char * n, const Date & d, int roll, float g): name(n), birthDate(d) {
cout << "Constructor::Student..\n";
rollNumber = roll;
gpa = g;
}
Output for Student aStudent("Fakhir", _date, 899, 3.5);:
Overloaded Constructor::Date..
Copy Constructor::Date..
Overloaded Constructor::String..
Constructor::Student..
Destructor::Student..
Destructor::String..
Destructor::Date..
Destructor::Date..
Note: birthDate(d) calls the Copy Constructor of the Date class.
Aggregation
Aggregation is a weaker relationship than composition. It models a βhas-aβ relationship where the parts can exist independently of the whole.
π Composition vs. Aggregation:
- Composition (Strong) : The part (e.g.,
String name) is created and destroyed with the composite object (e.g.,Student). The partβs life is dependent on the whole. - Aggregation (Weak) : One object uses the services of another, but both can exist independently. The relationship is typically implemented via pointers or references to the part object.
π Implementation: In aggregation, a class contains a pointer or reference to another object. The sub-object's lifetime is NOT dependent on the master class.
π Example: Room and Chair
class Room{
private:
float area;
Chair * chairs[50]; // Aggregation: array of pointers to Chair objects
public:
Room();
void AddChair(Chair *, int chairNo);
Chair * GetChair(int chairNo);
bool FoldChair(int chairNo);
};
int main(){
Chair ch1; // Chair object exists independently
{
Room r1; // Room object created
r1.AddChair(&ch1, 1); // Room uses Chair (aggregation)
r1.FoldChair(1);
} // Room r1 is destroyed, but ch1 is NOT destroyed
ch1.UnFoldChair(1); // ch1 still exists
return 0;
}
π‘ Why this matters: Aggregation allows for flexible object reuse. Multiple Rooms can share the same Chair, and the Chair can have its own independent lifecycle. The Room destructor does not delete the Chair objects.
Friend Functions
Friend functions are non-member functions that are granted access to all private members of a class.
π Friend Function: A function that is NOT a member of the class but is given the same access privileges as member functions.
Why are they needed? They are useful for operator overloading (e.g., << and >>), for creating functions that operate on objects from multiple classes, or for creating standalone utility functions that require private data.
Are they against OOP? Yes, friend functions violate the principle of encapsulation by allowing outside functions to access a classβs private internals. However, they are sometimes necessary for practical reasons, especially when implementing certain operators.
π Example Syntax:
class X{
private:
int a, b;
public:
void MemberFunction();
friend void DoSomething(X obj); // Declaration (friend keyword used here)
};
The definition of the friend function is:
void DoSomething(X obj){ // No 'friend' keyword in definition
obj.a = 3; // No error: private member accessible
obj.b = 4;
}
Important rules:
- The prototype of the friend function appears in the class definition (with
friendkeyword), but it is NOT a member function. - The
friendkeyword can be placed anywhere in the class (private, public, or protected) without affecting it. - The definition must NOT use the
friendkeyword.
Friend Classes
A class can be declared as a friend of another class. All member functions of the friend class then have access to the private members of the other class.
π Friend Class: A class whose member functions can access the private and protected members of the class that declared it as a friend.
π Example:
class X{
friend class Y; // Y is a friend of X
private:
int x_var1, x_var2;
};
class Y{
private:
int y_var1, y_var2;
public:
X objX; // Y has an X object as a member
void setX(){
objX.x_var1 = 1; // Y can access X's private members
objX.x_var2 = 2;
}
};
β Key Takeaways
Composition and aggregation are both forms of βhas-aβ relationships, but they differ fundamentally in ownership and lifecycle management. Composition implies that the part is owned by the whole and cannot exist without it (e.g., a Student's Name), whereas aggregation implies the part can exist independently and is often referenced via a pointer (e.g., a Roomβs Chairs). The member initialization list is the correct and most efficient way to construct embedded objects in composition. Friend functions are necessary for specific tasks like operator overloading, but they should be used sparingly as they break encapsulation. A class can also be made a friend of another, granting all its member functions access to that classβs private data.
π§ Quick Revision Questions
- Why is it better to use a member initialization list (e.g.,
: name(n)) instead of calling a setter method (e.g.,name.SetString(n)) inside the constructor body? - What is the essential difference in ownership between composition and aggregation?
- What C++ construct (pointer, reference, or value) is typically used to implement aggregation, and why?
- A function
void modify(X &obj)is declared asfriendin classX. In its definition, where should thefriendkeyword appear? - If class
Penis declared asfriend class Teacher;, what special access doesTeacherhave regardingPenobjects?
π Lecture 16 β Operator Overloading
π Overview: This lecture introduces operator overloading in C++, which allows user-defined types (like classes) to use standard operators (+, -, *, etc.) in a natural way. It explains why operator overloading is needed, the rules that govern it, and how to implement it for binary operators using member functions.
ποΈ Topics Covered
The lecture begins with the problem of using function calls like Add() for complex number operations, then introduces operator overloading as the solution. It covers the list of overloadable and non-overloadable operators, explains that precedence, associativity, and arity remain unchanged, and provides the general syntax for overloading operators as member and non-member functions. It concludes with a detailed example of overloading the + operator for a Complex class and discusses the importance of choosing the correct return type.
π Lecture Summary
16.1. Operator overloading
Consider a Complex class with real and img data members and functions like Add, Subtract, and Multiply. To add two complex numbers, you would write Complex c3 = c1.Add(c2);. This involves two operations: calling the Add function and copying the result using the copy constructor. However, there are issues: you cannot use the natural + operator (writing c1 + c2 gives an error), and chaining expressions like c1 + c2 + c3 + c4 is cumbersome and requires nested function calls like c1.Add(c2.Add(c3.Add(c4))). This makes code less readable, error-prone, and hard to maintain.
π Definition β Operator Overloading: The ability to define how standard operators (like +, -, *, etc.) behave when applied to objects of user-defined classes.
π‘ Why this matters: Operator overloading allows mathematical statements using user-defined objects to be written in a natural, readable way, just like with built-in types.
Operator overloading solves these issues. With an overloaded + operator, you can write c1 + c2 + c3 + c4, which the compiler converts into appropriate function calls like (c1.operator+(c2)).operator+(c3). C++ already overloads operators for predefined types (like int, float, double) and calls the correct low-level function (e.g., Add(int a, int b) for integers). Operator functions are not called directly; they are automatically invoked by the compiler.
π Definition β Precedence: The order in which operators are evaluated in an expression. Precedence is NOT affected by overloading. For example, in c1 * c2 + c3, multiplication is always done first, regardless of overloading.
π Definition β Associativity: The order in which operators of the same precedence are evaluated (left-to-right or right-to-left). Associativity is NOT changed by overloading. For example, c1 + c2 + c3 + c4 is evaluated left-to-right as ((c1 + c2) + c3) + c4.
π Definition β Arity: The number of operands an operator works on (e.g., unary for one, binary for two). Arity is NOT affected by overloading. For example, the division operator / always takes exactly two operands.
Important rules: Always write code that matches the operator's intended meaning (e.g., don't put subtraction code inside the + operator). Creating a new operator (like $) is a syntax error.
π Definition β General syntax for Operator Overloading:
As a member function: return_type class_name::operator operator_symbol( parameters ){ /*code*/ }
As a non-member (friend) function: return_type operator operator_symbol( parameters ){ /*code*/ }
Binary Operators Overloading
Binary operators act on two quantities. The general syntax for a member function is: TYPE class_name::operator operator_symbol( TYPE rhs ){ /*code*/ }. For a non-member function: TYPE operator operator_symbol( TYPE lhs, TYPE rhs ){ /*code*/ }. The operator OP must have at least one formal parameter of a user-defined class type. int operator + (int, int); is an error because you cannot redefine built-in operators for built-in types.
π Example β Overloading + for the Complex class:
class Complex {
private:
double real, img;
public:
Complex operator +(const Complex & rhs);
};
Complex Complex::operator +(const Complex & rhs) {
Complex t;
t.real = real + rhs.real;
t.img = img + rhs.img;
return t;
}
The return type is Complex to allow chaining, like Complex t = c1 + c2 + c3;. This is automatically converted to (c1.operator+(c2)).operator+(c3). If the return type were void, you could not chain expressions, would have to store results in one of the existing objects, and the code would be less readable and harder to maintain.
β Key Takeaways
Operator overloading allows user-defined types to use standard operators naturally, solving the readability and maintainability issues of using explicit function calls like Add(). The core rules to remember are: precedence, associativity, and arity of an operator are never changed by overloading; you cannot create new operators; and the overloaded operator must have at least one user-defined type parameter. For chaining expressions (like c1 + c2 + c3), the overloaded operator must return an object (or a reference) rather than void. Always ensure the overloaded operatorβs behavior is intuitive (e.g., + should add, not subtract) to avoid code chaos.
π§ Quick Revision Questions
- What is operator overloading and what problem does it solve?
- Name three operators that cannot be overloaded in C++ and explain why for one of them.
- If you overload
*for a class, can its precedence change compared to the built-in*? Explain. - Why is it important for a binary
+operator to return an object (e.g.,Complex) rather thanvoid? - What is the general syntax for overloading a binary operator as a member function of a class?
π Lecture 17 β Binary operators (cont.)
π Overview: This lecture continues the discussion on overloading binary operators, focusing on the complexities of adding basic data types to user-defined classes like Complex. It also introduces the critical topic of overloading the assignment operator, explaining why the compiler-generated version fails for classes with dynamic memory and how to implement a correct, deep-copying version.
ποΈ Topics Covered
The lecture covers the invocation mechanism for overloaded binary operators with respect to the left-hand argument. It then details how to modify the Complex class to handle addition with a double value, including the use of friend functions to solve the ordering problem. Finally, it delves into overloading the assignment operator, contrasting shallow and deep copy, identifying issues like memory leaks and dangling pointers, and demonstrating the correct signature and implementation that returns a reference.
π Lecture Summary
Binary operators (cont.)
The binary operator is always called with reference to the left-hand argument. For example, in c1+c2, the call becomes c1.operator+(c2), where c1 is the calling object and c2 is the argument. This behavior is fundamental to understanding how operators work from the perspective of an object.
π Example:
c1 + c2βc1.operator+(c2)c2 + c1βc2.operator+(c1)
Adding basic data type to complex number class
The standard overloaded + operator for a Complex class can add two Complex objects but cannot handle c1 + 2.325 (adding a double to a Complex). To support this, we modify the class by adding a specific overloaded member function.
class Complex{
// ...
Complex operator+(const Complex & rhs);
Complex operator+(const double& rhs);
};
The implementation for the double version simply adds the double to the real part and keeps the imaginary part unchanged. This now allows c1 + 235.01.
π Definition β Left-hand Argument Issue: When the left-hand operand is not an object of the class (e.g., 450.120 + c1), the compiler cannot find a member operator+ to call on the double. This requires a non-member function.
To solve this, we use friend functions that take both arguments explicitly. This allows us to write code for 450.120 + c1 where neither argument is the calling object.
class Complex{
// ...
friend Complex operator + (const Complex & lhs, const double & rhs);
friend Complex operator + ( const double & lhs, const Complex & rhs);
};
Why friend? Because these functions need access to the private members (real, img) of the Complex class. Alternatively, we could use getters and setters, but that would require four extra functions. The compiler searches for overloaded operators in member functions first, then in non-member (friend) functions.
Other Binary Operators
Other binary operators like *, /, and - are overloaded in a similar manner to the + operator. For a Complex class, these would be implemented as non-member friend functions to perform their respective arithmetic operations on the real and imaginary parts.
π Examples:
Complex operator * (const Complex & c1, const Complex & c2);Complex operator / (const Complex & c1, const Complex & c2);Complex operator - (const Complex & c1, const Complex & c2);
Overloading Assignment operator
The compiler can generate a default constructor, copy constructor, and assignment operator for a class. However, when a class has dynamic memory (e.g., a pointer), the compiler-generated assignment operator performs a shallow copy. This copies the pointer value, not the data it points to, leading to problems.
π Definition β Shallow Copy: A bitwise copy of each member, which for a pointer merely copies the address. This results in two pointers pointing to the same memory, causing memory leaks and dangling pointers.
Consider a String class with a char * bufferPtr. A shallow assignment str1 = str2 would copy the pointer bufferPtr from str2 to str1, losing the original memory str1 pointed to (memory leak) and leaving two objects sharing the same memory (dangling pointer issues).
π Example (Shallow Copy Problem):
str1points to "Hello",str2points to "World".- After
str1 = str2,str1.bufferPtrnow points to "World", but the memory for "Hello" is lost (leaked). Bothstr1andstr2point to the same "World" string.
Modified Assignment Operator Code
The correct assignment operator must perform a deep copy: delete the existing memory, allocate new memory, and then copy the data. The initial implementation often uses a void return type.
void String::operator = (const String & rhs){
size = rhs.size;
if(rhs.size != 0){
delete [] bufferPtr; // Free existing memory
bufferPtr = new char[rhs.size+1]; // Allocate new memory
strcpy(bufferPtr,rhs.bufferPtr); // Copy data
}
else
bufferPtr = NULL;
}
The Chaining Problem: A void return prevents chaining, e.g., str1 = str2 = str3. This expression is right-associative: str1 = (str2 = str3). First, str2.operator=(str3) is called, but because it returns void, the outer call str1.operator=(void) fails.
Return by Reference
To allow chaining, the assignment operator should return a reference to the object (*this). This allows expressions like str1 = str2 = str3 to work correctly, as the result of the inner assignment (str2 = str3) is the object str2, which is then passed to the outer assignment.
class String{
// ...
String & operator = (const String &);
};
String & String :: operator = (const String & rhs){
size = rhs.size;
delete [] bufferPtr;
if(rhs.size != 0){
bufferPtr = new char[rhs.size+1];
strcpy(bufferPtr,rhs.bufferPtr);
}
else bufferPtr = NULL;
return *this; // Return the current object by reference
}
π Definition β *this: this is a pointer to the current object. Dereferencing it with *this gives the object itself. Returning *this allows chaining.
π‘ Why this matters: The assignment operator returning a reference is a standard convention in C++ enabling idiomatic code and is essential for correct operation with standard library containers and algorithms.
β Key Takeaways
- A binary operator like
+is invoked on the left-hand operand. To handle cases where the left operand is not a class object (e.g.,double + Complex), you must use non-member friend functions. - When overloading operators for classes with dynamic memory, the compiler-generated default assignment operator performs a shallow copy, leading to memory leaks and dangling pointers.
- You must overload the assignment operator to perform a deep copy. This involves deleting the old memory, allocating new memory, and copying the data.
- The overloaded assignment operator should always return a reference to the current object (
*this). This supports chaining (e.g.,a = b = c) and is a standard C++ convention. - The order of search for an overloaded operator is: member functions first, then non-member functions.
π§ Quick Revision Questions
- Explain why the expression
450.120 + c1fails when only a member operator+ is defined forComplex + double. What is the solution? - What is a shallow copy, and what are two specific memory management issues it causes when used with a class that has a dynamically allocated array?
- Why is it necessary to
delete [] bufferPtrinside the overloaded assignment operator before allocating new memory? - What is the purpose of returning
*thisfrom the assignment operator? What problem does it solve? - To add a
doubleto aComplexobject, three overloadedoperator+functions were discussed. List the signatures for all three.