π Lecture 07 β The basic concept βObjectβ of Object Orientation (thinking in terms of objects) is realized using classes in programming languages.
π Overview: This lecture introduces the fundamental concept of classes in C++ as the mechanism to realize objects in programming. It explains how classes allow us to create user-defined types that capture both attributes and behaviours of real-world entities, and covers the syntax, access specifiers, and member access methods essential for implementing Object-Oriented Programming.
ποΈ Topics Covered
This lecture covers the definition and purpose of classes as the implementation mechanism for objects in C++. It explains how classes are used to create user-defined types (like Student or Circle) with data members and member functions. The lecture also discusses abstraction (including only relevant details), the difference between structure and class definitions, and the syntax for declaring class variables and accessing their members using dot and arrow operators. Finally, it covers the three access specifiers (public, private, protected) and the default private access specifier in classes.
π Lecture Summary
07.1. Class
A class is the mechanism given by C++ to realize objects in a program. It is the concrete implementation of objects in C++. We capture any object's attributes and behaviour in a programming language using classes. In other words, a class can be defined as a facility given by C++ to create new types according to our requirement. A class is a composite data type made from basic C++ types like integers, chars, and floats.
π Definition β Class: A way (mechanism) given by C++ to realize objects in a program; a concrete implementation of objects; a facility to create new user-defined types according to our requirement.
π‘ Why this matters: When we hear the word "student" or think about a student, a sketch comes to mind along with its attributes (name, roll number, class, degree) and behaviour (study, register). We need to capture these characteristic features of any object in the programming language, and the concept of class is used for this purpose.
Uses: Objects are structured in terms of class so our problem becomes easier to understand in terms of a C++ program. We can implement interactions easily in terms of classes. Student objects will interact with each other to take and give services to each other as happens in real life and is mapped in object-oriented programming approach.
07.2. Type in C++
We implement generic concepts using types. We have to model the generic concept of "Student," but there is no built-in type "student" in C++ like built-in C++ types int or float. A class is the mechanism in C++ that will allow us to define Student as a user-defined type. Similarly, the generic concept "Circle" will also be implemented in the same way.
As objects have attributes and behaviour, corresponding classes will also have data members and methods.
Example: For a Person object "Ali", the corresponding class has:
- Characteristics (attributes): Name, Age
- Behaviour (operations): Walks, Eats
class Person {
private: // attributes are generally made private
char name[]; // char array to store name
int age; // int to store age
public: // methods are generally made public
Person(); // constructor used to initialize data members
void walks(); // method walk
void eats(); // method eats
};
07.3. Abstraction
Abstraction means we only include those details in the system that are required for making a functional system. We leave out irrelevant attributes and behaviour from our objects.
Example for Student: Relevant to our problem β Name, Address. Not relevant to our problem β Sibling, Father's Business.
07.4. Defining a New User Defined Type
There are two ways to create user-defined types for objects in C++:
Structure Definition: Partially we can use structures to define an object. In C, we cannot define functions in a structure; however, in C++ we can add functions in both structures and classes.
Class Definition: Uses the keyword class (lowercase) followed by the ClassName.
class ClassName {
Access Specifier: (public, private, or protected)
DataType MemberVariable;
... .... ...
Access Specifier: (public, private, or protected)
ReturnType MemberFunction();
... .... ...
};
Example:
class Student {
private:
int rollNo;
char *name;
float CGPA;
char *address;
public:
void setName(char *newName);
void setRollNo(int newRollNo);
};
Why Member Functions: They model the behaviours of an object. Objects can make their data invisible (in accordance with the principle of data hiding). Setters and getters functions are provided by the class to access its members. This minimizes the chances of moving the objects into an inconsistent state because we can write checks in our setter functions. For example, we can check that whether the user has entered a correct age value and has not entered a negative value for age.
π‘ Why this matters: Using setters with validation keeps the object in a consistent state.
Student aStudent;
aStudent.rollNo = 514;
aStudent.rollNo = -514; // Error: this would put object in inconsistent state if allowed
07.5. Object and Class
An object is an instantiation of a user-defined type or class. Once we have defined a class, we can create as many objects for that class as we require.
Declaring class variables: Variables of classes (objects) are declared just like variables of structures and built-in data types.
TypeName VariableName;
int var; // declaring built-in int data type variable
Student aStudent; // declaring user-defined class Student object
07.6. Accessing members
Members of an object can be accessed using:
a. dot operator (.) β to access via the variable name:
Student aStudent; // declaring Student object
aStudent.rollNo = 5;
b. arrow operator (->) β to access via a pointer to an object:
Student * aStudent = new Student(); // declaring and initializing Student pointer
aStudent->rollNo = 5;
Note: It is against the principle of OOP to access the data members directly using an object of a class as we have done above. This code is given for example only. We should write accessor functions (setters and getters) wherever we want to access the members of the class.
Member functions are accessed in the same way using dot or arrow operator.
class Student {
int rollNo;
void setRollNo(int aNo);
};
Student aStudent;
aStudent.setRollNo(5);
Student *ptr_student = new Student();
ptr_student->setRollNo(5);
07.7. Access specifiers
Access specifiers are used to enforce access restrictions to members of a class. There are three access specifiers:
public: Used to tell that a member can be accessed whenever you have access to the object.private: Used to tell that a member can only be accessed from a member function of the same class.protected: To be discussed when we cover inheritance.
Example Program:
class Student {
char * name;
int rollNo;
public:
void setName(char *);
void setRollNo(int aNo);
};
void Student::setName(char * aName) {
if (strlen(aName) > 0) {
name = new char[strlen(aName)];
strcpy(name, aName);
}
}
void Student::setRollNo(int arollNo) {
if (arollNo > 0)
rollNo = arollNo;
}
int main() {
Student aStudent;
aStudent.rollNo = 5;
/* Error: we can not access private member of the class. */
aStudent.name = "Ali";
/* Error: we can not access private member of the class */
aStudent.setRollNo(1);
aStudent.setName("Ali");
/* Correct way to access the data member using public setter functions */
}
Default access specifier: When no access specifier is mentioned, then the default access specifier is private.
Example: The following two class definitions are equivalent:
class Student {
char * name;
int RollNo;
};
// Is equivalent to:
class Student {
private:
char * name;
int RollNo;
};
π‘ Why this matters: If you forget to write public: before the methods, they will be treated as private and will not be accessible outside the class.
β Key Takeaways
A class is the fundamental mechanism in C++ for implementing the concept of objects, allowing us to create user-defined types that encapsulate both data members (attributes) and member functions (behaviours). The principle of abstraction requires us to include only relevant attributes and behaviours for the system being built. Classes support data hiding by using access specifiers: public members are accessible outside the class, while private members can only be accessed through member functions (like setters and getters), with private being the default when no specifier is mentioned. Member functions, especially setters, should include validation logic to keep objects in a consistent state and prevent invalid data (like negative roll numbers). Objects are instantiated from classes and their members are accessed using the dot operator (.) for objects or the arrow operator (->) for pointers to objects, though direct access to data members violates OOP principles.
π§ Quick Revision Questions
- What is the difference between a class and an object in C++?
- What are the three access specifiers in C++ and what does each one mean?
- What is the default access specifier in a C++ class when no specifier is mentioned?
- Why should we use setter functions instead of directly accessing data members of a class?
- Explain the two operators used to access members of a class and when each is used.
π Lecture 08 β Member Functions
π Overview: This lecture covers how to define member functions in C++ classes, including inline functions for performance optimization. It introduces constructors for object initialization, constructor overloading, default constructors, copy constructors, and the critical difference between shallow copy and deep copy when dealing with dynamic memory.
ποΈ Topics Covered
Member functions and their definition inside and outside the class. Inline functions and their optimization benefits. Constructors, their properties, and default constructors. Constructor overloading with multiple parameters and default parameter values. Copy constructors and when they are called. Shallow copy versus deep copy, including the dangling pointer problem and its solution.
π Lecture Summary
08.1. Member Functions
Member functions are the functions that operate on the data encapsulated in the class. Public member functions serve as the interface to the class, allowing external code to interact with the object's data through these functions.
08.2. Defining Member Functions
We can define member functions in two ways:
a. We can define member functions of the class inside the class definition.
b. We can declare member function inside the class definition and define them outside the class. In this case, class definition is added in a .h file and implementation code is added in a .cpp file.
Function definition inside the class:
π Syntax:
class ClassName {
...
public:
ReturnType FunctionName() {
...
}
};
π Example:
class Student{
int rollNo;
public:
void setRollNo(int aRollNo){
rollNo = aRollNo;
}
};
Function definition outside the class:
π Syntax: Use the scope resolution operator :: to tell the compiler which class the function belongs to.
class ClassName {
...
public:
ReturnType FunctionName();
};
ReturnType ClassName::FunctionName() {
...
}
π Example:
class Student{
int rollNo;
public:
void setRollNo(int aRollNo);
};
void Student::setRollNo(int aRollNo){
rollNo = aRollNo;
}
08.3. Inline Functions
Inline functions are a way used by compilers to improve efficiency of the program. When functions are declared inline, the normal process of function calling (using stack) is not followed; instead, the function code is added by the compiler at all points where these functions have been called. Normally, small size functions that need to be called many times during program execution are declared inline. Inline functions decrease code execution time because the program doesn't involve function call overhead. The keyword inline is used to request the compiler to make a function inline. However, using the inline keyword with a function does not guarantee that the function will definitely be inlined β it depends on the compiler.
π Example:
inline int Area(int len, int hi) {
return len * hi;
}
int main() {
cout << Area(10,20);
return 0;
}
π‘ Why this matters: The functions defined inside the class are by default inline (whether we mention the keyword inline with them or not). In case we define a function outside the class, then we must use the keyword inline to make the function inline.
π Example β Inline inside the class (automatic):
class Student{
int rollNo;
public:
void setRollNo(int aRollNo){ // automatically inline
rollNo = aRollNo;
}
};
π Example β Inline outside the class (must use keyword):
class Student{
...
public:
inline void setRollNo(int aRollNo);
};
inline void Student::setRollNo(int aRollNo){
rollNo = aRollNo;
}
08.4. Constructor
A constructor is used to initialize the objects of a class. It ensures that the object is in a well-defined state at the time of creation. The constructor of a class is automatically generated by the compiler; however, we can write it ourselves as well. The constructor is automatically called when the object is created. Constructors are not usually called explicitly by us.
08.5. Constructor Properties
- A constructor is a special function having the same name as the class name
- A constructor does not have a return type (not even
void) - Constructors are commonly public members
π Example:
class Student{
int rollNo;
public:
Student(){ // Constructor
rollNo = 0;
}
};
int main() {
Student aStudent; // constructor is implicitly called at this point
}
08.6. Default Constructor
A default constructor is a constructor without any parameters or with all parameters having default values. If we do not define a default constructor, the compiler will generate one. The compiler-generated default constructor is called implicit, and the user-written default constructor is called explicit. The compiler-generated default constructor initializes data members to their default values.
β οΈ Important Rule: If we have given any constructor for a class (whether explicit default or with parameters), then the compiler will not create an implicit default constructor.
π Example β No constructor defined, compiler generates one:
class Student {
int rollNo;
char *name;
float GPA;
public:
// no constructors
};
π Compiler-generated implicit default constructor code:
{
rollNo = 0;
GPA = 0.0;
name = NULL;
}
08.7. Constructor Overloading
We can write constructors with parameters as well. These parameters are used to initialize the data members with user-supplied data (passed as parameters). This is known as constructor overloading β having multiple constructors with different parameter lists.
π Example β Student class with four constructors:
class Student{
int rollNo;
char *name;
float GPA;
public:
Student(); // explicit default constructor
Student(char * aName); // one parameter
Student(char * aName, int aRollNo); // two parameters
Student(int aRollNo, int aRollNo, float aGPA); // three parameters
};
π Creating objects using different constructors:
int main() {
Student student1; // default constructor
Student student2("Name"); // one parameter constructor
Student student3("Name", 1); // two parameter constructor
Student student4("Name", 1, 4.0); // three parameter constructor
}
08.8. Constructor Overloading with Default Parameters
We can use default parameter values to reduce the writing effort. In that case, we write only one constructor and it serves the purpose of all constructors.
π Example:
Student::Student(char * aName = NULL, int aRollNo = 0, float aGPA = 0.0) {
// initialization code
}
This single constructor is equivalent to all four separate constructors and will use default values if values are not passed as arguments while creating objects.
08.9. Copy Constructor
Copy constructors are used when:
- Initializing an object at the time of creation (creating an object with the state of a pre-existing object)
- When an object is passed by value to a function (a temporary copy of the object is created on the stack)
π Syntax:
Student::Student(const Student &obj) {
/* copying values to newly created object */
rollNo = obj.rollNo;
name = obj.name;
GPA = obj.GPA;
}
π Example:
int main() {
Student aStudent; // default constructor called
Student bStudent = aStudent; // copy constructor called
}
void func1(Student student) { // copy constructor called to create temporary student object
...
}
int main() {
Student studentA;
func1(studentA); // copy constructor called here
}
As with the default constructor, the compiler also generates a copy constructor by itself; however, we can override that copy constructor by writing our own.
08.10. Shallow Copy
When we initialize one object with another, the compiler copies the state of one object to the other using the copy constructor by assigning data member values of the previous object to the newly created object. This kind of copying is called shallow copying.
π Shallow copy using default Copy Constructor:
Student::Student(const Student &obj) {
rollNo = obj.rollNo;
name = obj.name; // copies pointer, not the data it points to
GPA = obj.GPA;
}
π Example:
Student studentA;
Student studentB = studentA; // Shallow copy
π‘ Why this matters: Shallow copy works fine if our class does not include dynamic memory allocation. However, in case of dynamic memory allocation, it leads to the dangling pointer problem. When studentB is created as a shallow copy of studentA, both objects point to the same memory location for the name data member (if it's a char* using dynamic memory). If studentA is deleted, its destructor frees the memory. Now studentB's name pointer still points to that freed memory area β this is a dangling pointer. Also, changing studentA's name would also change studentB's name since they share the same memory.
08.11. Deep Copy
We write our own deep copy code in the copy constructor so that when we create a new object from an existing object using the copy constructor, we also allocate new dynamic memory for data members involving dynamic memory.
π Deep Copy implementation:
Student::Student(const Student &obj) {
int len = strlen(obj.name);
name = new char[len+1]; // allocate new memory
strcpy(name, obj.name); // copy the actual string content
// copy rest of the data members in the same way
rollNo = obj.rollNo;
GPA = obj.GPA;
}
π Example β Using deep copy creates separate memory for both objects:
Student studentA;
Student studentB = studentA; // now copy constructor performs deep copy
// studentA and studentB have their own separate memory for name
Rule: In case our class does not involve dynamic memory, the default copy constructor that performs shallow copy works fine. In case our class has any data member involving dynamic memory, we must write our own code to perform deep copy.
β Key Takeaways
Member functions are defined either inside the class (automatically inline) or outside using the scope resolution operator (needing the inline keyword explicitly). Inline functions improve performance by replacing function call overhead with the function's code, but the compiler decides whether to actually inline them. Constructors are special functions with the same name as the class, no return type, and are automatically called when objects are created. If no constructor is written, the compiler generates an implicit default constructor; however, if any constructor is defined, the compiler will not generate one. Constructor overloading allows flexibility in object initialization, and default parameter values can reduce the number of constructors needed. Copy constructors are used when creating objects from existing ones or passing by value, and they can perform either shallow copy (default, copies pointers) or deep copy (user-written, allocates new memory). Shallow copy causes the dangling pointer problem and unintended data sharing when dynamic memory is involved, so deep copy is essential for classes with dynamically allocated data members.
π§ Quick Revision Questions
- What are the two ways to define member functions in C++ classes, and when does a function become automatically inline?
- What are the three key properties of a constructor, and what happens if you do not define any constructor in a class?
- When does the compiler NOT generate an implicit default constructor?
- What are the two specific situations where a copy constructor is automatically called?
- Explain the difference between shallow copy and deep copy, and describe the problem that arises when shallow copy is used with dynamically allocated data.
π Lecture 09 β Review
π Overview: This lecture covers the copy constructor in depth, including when it is called, the difference between shallow and deep copy, and the problems that arise with dynamic memory. It also reviews the destructor, its syntax and sequence of calls, accessor functions for data hiding, and the
thispointer which allows member functions to operate on the correct object.
ποΈ Topics Covered
The lecture begins with a review of copy constructors and when they are invoked. It then explains shallow copy and its pitfalls with dynamic memory, followed by deep copy as the solution. Important points about copy constructors are summarized. The destructor is covered with its syntax, limitations (no overloading), and call sequence. Finally, accessor functions (getters and setters) and the this pointer (how it works and is passed) are explained.
π Lecture Summary
Copy Constructor
A copy constructor is used to initialize an object at the time of creation using the state of a pre-existing object. It is also called when an object is passed by value to a function, because a temporary copy of the object is created on the stack. The compiler generates a default copy constructor, but we can override it.
π Definition β Copy Constructor: A constructor that initializes an object using another object of the same class. It is called when: (1) initializing an object with another object (e.g., Student studentB = studentA;), and (2) passing an object by value to a function (e.g., func1(studentA);).
π Formula/Syntax: Student::Student(const Student &obj) { /* copy data members */ } β The copy constructor takes a const reference to the source object to avoid modification and infinite recursion.
π Example: Student studentA; Student studentB = studentA; β Copy constructor is called to create studentB from studentA. Also, void func1(Student student) β when called as func1(studentA), the copy constructor creates the temporary student parameter.
09.1. Shallow Copy
Shallow copy is the default copying mechanism provided by the compiler. It copies the values of data members directly from the source object to the new object. This works fine when the class does not involve dynamic memory allocation. However, when a data member is a pointer to dynamically allocated memory, shallow copy causes both objects to point to the same memory location. This leads to two major problems: dangling pointers (when one object is destroyed, the other's pointer becomes invalid) and unintended data modification (changing the value via one object affects the other).
π Definition β Shallow Copy: A bitwise copy of an object where the data member values of the source object are simply assigned to the new object's data members.
π Example (Problem):
Student studentA("AHMAD",1); // name points to heap memory containing "AHMAD"
Student studentB = studentA; // Shallow copy: studentB.name = studentA.name (same address)
// If studentA is deleted, studentB.name becomes a dangling pointer.
π‘ Why this matters: Shallow copy with dynamic memory leads to undefined behavior because two objects share the same memory, and the destructor of one will free the memory while the other still points to it.
09.2. Deep Copy
Deep copy solves the problems of shallow copy by writing custom code in the copy constructor that allocates new dynamic memory for pointer data members of the new object and then copies the content (not just the address). This ensures each object has its own independent copy of the data.
π Definition β Deep Copy: A copy operation that allocates separate memory for dynamically allocated data members in the new object and copies the actual data (e.g., using strcpy) rather than just the pointer address.
π Formula/Syntax:
Student::Student(const Student &obj) {
int len = strlen(obj.name);
name = new char[len+1]; // allocate new memory
strcpy(name, obj.name); // copy the content
rollNo = obj.rollNo;
}
π Example: With deep copy, Student studentB = studentA; now creates studentB.name as a separate block of memory containing "AHMAD". Deletion of studentA does not affect studentB, and vice versa.
09.3. Important points about copy constructor:
- If the class does not involve dynamic memory, the default copy constructor (shallow copy) works fine.
- If the class has any data member involving dynamic memory, we must write our own copy constructor to perform deep copy.
- Copy constructor is normally used to perform deep copy.
- If we do not make a copy constructor, the compiler performs shallow copy.
- Shallow copy performs bitwise copy.
09.4. Destructor
A destructor is a special member function used to free dynamically allocated memory and perform housekeeping operations when an object is destroyed. It has the same name as the class, preceded by a tilde ~. Destructors cannot be overloaded. Constructors and destructors are called automatically: constructors are called in the order objects are declared, while destructors are called in the reverse order.
π Definition β Destructor: A function with the same name as the class, preceded by ~, that is automatically called when an object goes out of scope. It is used to release resources (e.g., memory allocated with new).
π Syntax: ~Student() { if(name) { delete []name; } }
π Example (Sequence):
int main() {
Student studentB("Ali"); // "Ali Constructor" printed
Student studentA("Ahmad"); // "Ahmad Constructor" printed
return 0;
}
// Output:
// Ali Constructor
// Ahmad Constructor
// Ahmad Destructor
// Ali Destructor
Destructors are called in reverse order of declaration.
09.5. Accessor Functions
According to the principle of information hiding, data members are declared as private. Accessor functions provide a controlled interface to get (getter) and set (setter) the private data. We add error checking code in setter functions to prevent the object from entering an illegal state. A good practice is to never return a handle (reference or pointer) to a data member from a getter, because the caller could modify the private data.
π Definition β Accessor Functions: Public member functions that allow safe access to private data members. Setters modify values (with validation), and getters return values (by value, not by reference).
π Example (Setter with validation):
void Student::setRollNo(int aRollNo) {
if(aRollNo < 0) { rollNo = 0; } // error checking
else { rollNo = aRollNo; }
}
π Example (Getter):
int getRollNo() { return rollNo; } // returns a copy, not a reference
09.6. this Pointer
When a class is defined, the compiler reserves space for member functions, but memory for data members is allocated only when objects are created. The this pointer is an implicit parameter passed to every non-static member function. It holds the address of the object for which the function was called. This allows the function to access the correct object's data members. The function with n parameters is internally called with n+1 parameters, where the extra parameter is this. The declaration of this is DataType * const this; (the pointer itself is constant, you cannot change its address).
π Definition β this Pointer: A constant pointer that holds the memory address of the current object. It is automatically passed to all non-static member functions.
π Example:
Student::Student() { this->rollNo = 0; } // equivalent to rollNo = 0;
And void Student::setName(char *) is internally void Student::setName(char *, const Student *) where the second argument is this.
π Memory Layout: Multiple objects (e.g., s1, s2, s3) each have their own data memory. The function code is shared. The this pointer ensures that when s1.setRollNo(5) is called, the function acts on s1's data, not s2's.
β Key Takeaways
For the exam, you must understand when a copy constructor is called and the critical difference between shallow and deep copy. Remember that shallow copy (the default) is only safe for classes without dynamic memory; otherwise, it causes dangling pointers. Deep copy must be explicitly written in the copy constructor to allocate new memory for pointers. Destructors cannot be overloaded and are called in reverse order of construction. Accessor functions (getters/setters) enforce data hiding, and setters should include validation. Finally, the this pointer is an implicit parameter that allows member functions to operate on the correct object; it is always the address of the current object.
π§ Quick Revision Questions
- What are the two situations where a copy constructor is called?
- What is the core difference between shallow copy and deep copy?
- In the example with
Student studentA("AHMAD"); Student studentB = studentA;(using shallow copy), what happens whenstudentA's destructor runs? - Why can destructors not be overloaded, and in what order are destructors called for objects declared in the same scope?
- Explain why it is considered bad practice to return a reference (handle) to a data member from a getter function.
π Lecture 10 β Uses of this Pointer and const Member Functions
π Overview: This lecture explores two important C++ concepts: practical uses of the
thispointer, particularly for returning references to the current object, and the separation of interface from implementation in object-oriented programming. It also introduces constant member functions, explaining how they enforce read-only access and prevent accidental modification of object data.
ποΈ Topics Covered
The lecture covers uses of the this pointer for returning *this from functions to enable chaining, the separation of interface and implementation in C++ using header (.h) and implementation (.cpp) files, the Complex number class as an example of interface/implementation separation, constant member functions declared with the const keyword to ensure read-only access, and how the this pointer behaves in constant member functions.
π Lecture Summary
10.1. Uses of this Pointer
The this pointer is used when a designer wants to return a reference to the current object from a function. In such cases, the reference is obtained from this using the syntax *this. This is particularly useful for function chaining, where multiple functions can be called sequentially on the same object.
π Definition β this pointer: A special implicit pointer in C++ that points to the object for which a member function is called. It is automatically passed to all non-static member functions. π Example:
class Student {
int rollNo;
char name[50];
public:
Student setRollNo(int aNo) {
rollNo = aNo;
return *this; // returns reference to current object
}
Student setName(char *aName) {
strcpy(name, aName);
return *this; // returns reference to current object
}
};
int main() {
Student aStudent, bStudent;
bStudent = aStudent.setName("Ahmad");
// Chaining example:
bStudent = aStudent.setName("Ali").setRollNo(2);
return 0;
}
π‘ Why this matters: The *this pattern enables method chaining, allowing multiple operations to be written concisely in a single line.
10.2. Separation of Interface and Implementation
Public member functions exposed by a class are called its interface. Separation of implementation from the interface is good software engineering practice. The benefit is that we can easily change implementation without changing the interface.
In C++, we generally relate the concept of interface to the header (.h) file and implementation to the .cpp file. Functions are defined in the implementation file (.cpp) while the class definition is given in the header file (.h). This allows users to include only the header file to use the class.
Example of file structure:
// Student.h (interface)
class Student {
int rollNo;
public:
void setRollNo(int aRollNo);
int getRollNo();
};
// Student.cpp (implementation)
#include "student.h"
void Student::setRollNo(int aNo) {
// implementation code
}
int Student::getRollNo() {
// implementation code
}
// Main.cpp (using the class)
#include "student.h"
int main() {
Student aStudent;
return 0;
}
10.3. Complex Number
A complex number is represented as z = x + i y and has two representations:
- Euler form: Standard Cartesian representation with real part (x) and imaginary part (y)
- Phasor form:
z = |z| (cos ΞΈ + i sin ΞΈ)where|z|is the complex modulus andΞΈis the complex argument or phase
π Definition β UML Notation: A standard way to visualize class structure, showing private data members and public member functions. π Example of two implementations:
Old implementation (Cartesian form):
class Complex { // old
float x; // real part
float y; // imaginary part
public:
void setNumber(float i, float j) {
x = i;
y = j;
}
};
UML: Complex { -x: float; -y: float; +getX(): float; +getY(): float; +setNumber(float i, float j): void }
New implementation (Polar form):
class Complex { // new
float z; // magnitude
float theta; // angle
public:
void setNumber(float i, float j) {
z = sqrt(i*i + j*j);
theta = arctan(j/i);
}
};
UML: Complex { -z: float; -theta: float; +getX(): float; +getY(): float; +setNumber(float i, float j): void }
Advantages of separation:
- User is only concerned about ways of accessing data (interface)
- User has no concern about internal representation and implementation
10.4. const Member Functions
Constant member functions are functions that provide only read-only access to data. They are declared by placing the keyword const at the end of the parameter list. The compiler generates an error if these functions try to change the value of data members.
π Definition β const member function: A member function that cannot modify the state of any object; it is a "read-only" function.
Declaration syntax:
// Inside class:
class ClassName {
ReturnVal Function() const;
};
// Outside class definition:
ReturnVal ClassName::Function() const {
// code
}
π Example of correct usage:
class Student {
int rollNo;
public:
int getRollNo() const {
return rollNo; // OK - read-only access
}
};
Importance for error detection: Without const, a common typing mistake (using = instead of ==) can go undetected:
// Without const - buggy code that compiles
bool Student::isRollNo(int aNo) {
if(rollNo = aNo) { // assignment instead of comparison!
return true;
}
return false;
}
// With const - compiler catches the error
bool Student::isRollNo(int aNo) const {
if(rollNo = aNo) { // COMPILER ERROR - cannot modify data
return true;
}
return false;
}
Important rules:
- Constructors and destructors cannot be const because they modify the object to a well-defined state or clean up memory.
class Time { public: Time() const {} // error! ~Time() const {} // error! }; - Constant member functions cannot change data members.
- We cannot call non-constant functions inside constant functions, because non-constant functions may contain code that changes the object's state.
class Student { char *name; public: char *getName(); void setName(char *aName); int ConstFunc() const { name = getName(); // error - getName() is non-const setName("Ahmad"); // error - setName() is non-const } };
10.5. this Pointer and const Member Function
When a class function is called, an implicit this pointer is passed to tell the function which object it operates on. For constant member functions, the this pointer is passed differently:
π Definition β const this pointer in const functions: const Student *const this instead of Student *const this (for ordinary functions). This means the this pointer cannot be used to change the value of data members of the object.
π Key difference:
// For ordinary member functions:
Student * const this; // pointer is constant, but object is not
// For constant member functions:
const Student * const this; // both pointer and object are constant
π‘ Why this matters: The const version of this ensures that all member access via this is read-only, preventing accidental modification of object state even when using the this pointer directly.
β Key Takeaways
For the exam, you must understand that the this pointer enables method chaining through *this, and that separating interface (.h files) from implementation (.cpp files) is a fundamental software engineering principle that allows changing internal representation without affecting users. Constant member functions, marked with const after the parameter list, enforce read-only access and catch assignment-instead-of-comparison bugs at compile time. Constructors and destructors cannot be const. Non-constant functions cannot be called from within constant functions. Finally, in constant member functions, the implicit this pointer becomes const ClassName * const this, preventing any modification of object data through it.
π§ Quick Revision Questions
- What is the purpose of returning
*thisfrom a member function, and what pattern does it enable? - How does separating interface from implementation benefit the user of a class, as shown with the Complex number example?
- What is the correct syntax for declaring and defining a constant member function?
- Why can't constructors and destructors be declared as
const? - What is the difference between the
thispointer in an ordinary member function versus a constant member function?
π Lecture 11 β Usage Example of Constant Member Functions & Static Data Members
π Overview: This lecture covers two crucial C++ topics: how to properly initialize constant data members using member initializer lists, and the concept of static data members that are shared across all class instances. Understanding these mechanisms is essential for writing robust, memory-efficient object-oriented programs.
ποΈ Topics Covered
The lecture begins with a problem scenario requiring a constant roll number in a Student class, then explains the difference between initialization and assignment. It introduces member initializer lists as the solution for initializing constant members. The lecture then covers constant objects and their restriction to constant member functions, followed by a detailed explanation of static variables, static data members, their syntax, definition, initialization, and how they differ from instance variables.
π Lecture Summary
11.1. Usage example of Constant member functions
A problem is presented: we need a Student class where a student receives a roll number at object creation that cannot be changed afterwards. The existing class has a simple int rollNo data member. Simply making rollNo constant (const int rollNo) prevents modification, but creates an initialization dilemma β we cannot assign a value to rollNo in the constructor body because by the time constructor code executes, the constant member already exists and cannot be assigned.
π Definition β Constant data member (initialization problem): A data member declared with const cannot be assigned a value after it is created. This means neither declaration-time initialization (not allowed for non-static members in C++) nor constructor body assignment works.
π Example (error):
class Student {
const int rollNo;
public:
Student(int aRollNo) {
rollNo = aRollNo; // ERROR: cannot modify constant data member
}
};
π‘ Why this matters: Without proper initialization, constant members would be unusable. C++ provides a special syntax to solve this.
11.2. Difference between Initialization and Assignment
- Initialization: Assigning a value when a variable is created.
int i = 2;β memory is allocated and the value is set in one step.
- Assignment: Assigning a value after the variable has been created.
int i;theni = 7;β two separate steps: creation, then value assignment.
π Key insight: Constant members can be initialized (at creation) but cannot be assigned (after creation).
11.3. Member Initializer List
The member initializer list is the mechanism C++ provides to initialize data members at the moment they are created, before the constructor body executes.
- It appears after the closing parenthesis of the constructor's parameter list, preceded by a colon (
:). - For multiple members, use a comma-separated list.
- The syntax is:
ConstructorName(parameters) : member1(value1), member2(value2), ... { ... }
π Syntax: ClassName::ClassName(parameters) : member1(value1), member2(value2), ... { constructor body }
π Example (Student class solution):
class Student {
const int rollNo;
char *name;
float GPA;
public:
Student(int aRollNo) : rollNo(aRollNo), name(nullptr), GPA(0.0) {
// constructor body β rollNo already initialized
}
};
Order of Initialization: Data members are initialized in the order they are declared in the class, not in the order they appear in the initializer list.
π Example demonstrating order:
class ABC {
int x; // declared first
int y; // declared second
int z; // declared third
public:
ABC();
};
ABC::ABC() : y(10), x(y), z(y) {
// Initialization order: x first (junk value, because y not yet initialized)
// y second (10)
// z third (10)
}
Here, x gets a junk value because it is declared before y, even though x(y) appears before y(10) in the initializer list.
11.4. const Objects
Objects can be declared constant using the const keyword. Constant objects cannot change their state (their data members) after construction.
- A
constobject can only call const member functions β functions guaranteed not to modify the object. - Non-const member functions cannot be called on const objects (even if they don't actually modify state).
π Key rule: Make all member functions that do not change object state const by adding the const keyword after the function parameter list.
π Example (correct):
class Student {
int rollNo;
public:
int getRollNo() const { // const member function
return rollNo;
}
};
int main() {
const Student aStudent(5);
int a = aStudent.getRollNo(); // OK: getRollNo is const
return 0;
}
π Example (incorrect):
class Student {
int rollNo;
public:
int getRollNo() { // non-const member function
return rollNo;
}
};
int main() {
const Student aStudent(5);
int a = aStudent.getRollNo(); // ERROR: cannot call non-const function on const object
return 0;
}
11.5. Static Variables
Static variables inside a function have lifetime throughout the entire program, but are only visible within the function where they are declared.
- They are initialized only once, the first time the function is called.
- If not explicitly initialized, they are automatically initialized to 0.
π Example:
void func1(int i) {
static int staticInt = i; // initialized only on first call
cout << staticInt << endl;
}
int main() {
func1(1); // Output: 1 (staticInt initialized to 1)
func1(2); // Output: 1 (staticInt NOT re-initialized; still 1)
return 0;
}
Contrast with assignment version:
void func1(int i) {
static int staticInt; // initialized to 0 only once
staticInt = i; // assignment happens every call
cout << staticInt << endl;
}
int main() {
func1(1); // Output: 1
func1(2); // Output: 2
return 0;
}
Static Data Member
π Definition β Static data member: βA variable that is part of a class, yet is not part of any object of that class.β
Key characteristics:
- Shared by all instances (objects) of the class β one copy exists regardless of how many objects are created.
- Does not belong to any particular instance β it belongs to the class itself.
- Stored in class space (global/data segment), not in individual object memory.
Syntax:
- Declared inside the class with
statickeyword:class ClassName { static DataType VariableName; }; - Defined outside the class (at file scope):
DataType ClassName::VariableName;
Initialization:
- Static data members should be initialized once at file scope (at the point of definition).
- If not explicitly initialized, they are initialized to 0.
- Even private static members can be initialized at file scope using the
ClassName::syntax.
π Example:
class Student {
private:
static int noOfStudents; // declaration inside class
public:
// ...
};
int Student::noOfStudents = 0; // definition and initialization at file scope
// Note: private static member can be accessed outside class only for initialization
β Key Takeaways
- Constant data members (
constmembers) cannot be assigned in the constructor body or anywhere else β they must be initialized using a member initializer list, which runs before the constructor body executes. - Member initializer list initialization order follows the declaration order of data members in the class, not the order in the list β this can lead to subtle bugs if not understood.
- Constant objects can only call const member functions; to make a function const, add the
constkeyword after its parameter list. All getter functions that don't modify state should be declared const. - Static variables inside functions are initialized only once and retain their value across function calls. Static data members belong to the class (not objects), are shared by all instances, and must be defined and optionally initialized outside the class.
- The difference between initialization (value set at creation time) and assignment (value set after creation) is fundamental to understanding when member initializer lists are required versus optional.
π§ Quick Revision Questions
- Why can't you initialize a
constdata member by assigning a value to it inside the constructor body? - What is the syntax for a member initializer list, and how do you initialize multiple data members?
- If a class declares
int x; int y;and the constructor uses the initializer list: y(5), x(y), what value doesxget? Why? - What error occurs when a
constobject tries to call a non-const member function, and how do you fix it? - Where must a static data member be defined (as opposed to declared), and what happens if no explicit initial value is given?