π Lecture 23 β Preprocessor
π Overview: This lecture covers the C/C++ preprocessor, which modifies source code before compilation. It explains essential directives like
#includeand#define, how to create and use macros, and best practices for conditional compilation and debugging. Understanding the preprocessor is critical for writing efficient, portable, and maintainable C/C++ code.
ποΈ Topics Covered
The lecture begins by introducing the preprocessor and its role in enhancing C. It then covers the #include directive in detail, including angle bracket vs. quotation mark usage. The #define directive is explained for creating symbolic constants. A list of other preprocessor directives is given, with special attention to conditional compilation using #ifdef, #ifndef, #if, #else, #elif, and #endif for debugging. Macros are classified into simple and parameterized types, with detailed examples and precautions about parentheses. The lecture concludes with practical tips on writing header files and ensuring code portability.
π Lecture Summary
Preprocessor
The preprocessor is a tool that comes with every C compiler. It enhances the C language by making changes to the source code before the actual compilation. The compiler then receives this modified source code file. All preprocessor directives start with the # sign.
include directive
The #include directive replaces the line where it appears with the entire text of the specified file. There are two ways to use it:
#include <somefile>: The compiler searches for the file in a specific include directory (where standard header files likeiostream.h,stdlib.hare located). These files are typically called header files (extension.h).#include "myHeaderFile.h": The compiler first searches for the file in the current working directory (where the user's source code is located). This is used for user-defined header files.
When the compiler processes #include, it literally inserts the entire content of the included file into the source code at that point. This expanded source code is what the compiler sees. Including header files at points other than the start of the program is legal but not standard practice.
define directive
The #define directive is used to define symbolic constants (also called macros). The syntax is #define NAME value. For example:
#define PI 3.1415926
When the preprocessor encounters this directive, it replaces every occurrence of PI in the code with 3.1415926 before the compiler sees the code. This is a text substitution. Using #define for constants is better than using variables because the value cannot be accidentally changed and it allows for easy updatesβchanging the value in one place updates the entire program. Symbolic constant names are conventionally written in UPPERCASE.
π Definition β Macro: A special name that is substituted in the code by its definition, resulting in an expanded code block before compilation.
π‘ Why this matters: Unlike a variable (double Pi = 3.1415926;), a #define constant cannot be reassigned. This ensures the value remains constant throughout the program. Also, if the same constant is used across multiple files, defining it in a single header file and including that file ensures all files get the updated value when changed.
π Formula: #define NAME value β NAME is replaced by value as literal text everywhere in the code.
Other Preprocessor Directives
The lecture lists several preprocessor directives, including #undef, #ifdef, #ifndef, #if, #else, #elif, #endif, #error, #line, #pragma, and #assert. The focus is on conditional compilation.
Conditional Compilation allows parts of the code to be compiled only if certain conditions are met. For example, during debugging, programmers often insert output statements to check variable values. Instead of manually removing all these lines later, they can use #define DEBUG and then enclose debug code within:
#ifdef DEBUG
cout << "Control is in the while loop...";
#endif
If DEBUG is defined, the code inside is compiled; otherwise, it is ignored.
The #undef directive is used to undefine a previously defined symbol (e.g., #undef PI). After this line, PI is no longer available. A symbol cannot be redefined without being undefined first.
The lecture mentions that header files often contain constructs like #ifdef cplusplus ... extern "C" { ... #endif to ensure compatibility between C and C++ code.
Macros
Macros are classified into two categories:
-
Simple Macros: Map a symbolic name to a constant (e.g.,
#define PI 3.1415926). -
Parameterized Macros: Take arguments. For example:
#define square(x) x * xThe
#definestatement is not C code, so no semicolon is needed at the end.β οΈ Critical Pitfall: The simple
#define square(x) x * xhas a precedence problem. Forsquare(i + j), the substitution becomesi + j * i + j, which is incorrect due to operator precedence (*binds before+).Correct Definition: Always put parentheses around the entire macro definition and around each argument.
#define square(x) ((x) * (x))Now
square(i + j)becomes((i + j) * (i + j)), which is correct.π‘ Macro vs. Function: A macro is expanded inline at compile time, so there is no function call overheadβno pushing arguments onto the stack, no jumping to a function, no returning. This makes macros faster. However, if a macro is used many times, the code becomes bloated (repeat code at each usage), potentially enlarging the executable. Functions are better for complex operations. Macros are best for simple, one-line substitutions.
Rules for defining parameterized macros:
- No space between the macro name and the opening parenthesis.
- Arguments are separated by commas.
- Always use parentheses around the entire definition and each argument.
π Formula β Parameterized Macro: #define MACRO_NAME(ARG1, ARG2) ((ARG1) * (ARG2)) β ARG1 and ARG2 are textually replaced in the definition, with parentheses ensuring correct evaluation.
π Example (Parameterized Macro):
#include <iostream.h>
#define square(x) ((x) * (x))
main() {
int x;
cout << "Enter value of x: ";
cin >> x;
cout << "Square of x = " << square(x) << endl; // Replaced: ((x) * (x))
cout << "Square of x+2 = " << square(x+2) << endl; // Replaced: ((x+2) * (x+2))
cout << "Square of 7 = " << square(7); // Replaced: ((7) * (7))
}
Example
A complete program demonstrating macros for calculating the area of a circle:
#include <iostream.h>
#define PI 3.14159
#define CIRCLEAREA(X) (PI * (X) * (X))
main() {
float radius;
cout << "Enter radius of the circle: ";
cin >> radius;
cout << "Area of circle is " << CIRCLEAREA(radius);
}
The macro CIRCLEAREA uses the already defined PI constant. The parentheses ensure correct evaluation even for expressions like CIRCLEAREA(radius + 2).
The lecture also discusses portability. Standard header files (like iostream.h) have consistent names across different compilers and operating systems, making C code highly portable. User-defined header files, containing function prototypes, symbolic definitions, and macros, can be ported along with the source code, centralizing common utilities and easing code maintenance.
Tips
- All preprocessor directives start with the
#sign. - A symbol cannot be redefined without undefining it first.
- Conditional compilation directives help in debugging.
- Do not declare variable names starting with underscore (reserved for compiler internals).
- Always use parentheses when defining macros that take arguments.
β Key Takeaways
The preprocessor modifies source code before compilation, and all its directives begin with #. The #include directive inserts the contents of a file; use angle brackets for standard library headers and quotation marks for user-defined files. The #define directive creates macros for symbolic constants or parameterized code snippets, and for parameterized macros, always wrap the entire definition and each parameter in parentheses to avoid precedence errors. Macros eliminate function call overhead but increase code size, so use them for simple, frequently used operations. Conditional compilation with #ifdef, #ifndef, #if, #else, and #endif is essential for portable code and efficient debugging.
π§ Quick Revision Questions
- What is the difference between
#include <filename>and#include "filename"in terms of where the preprocessor searches for the file? - Why must all parameters and the entire expression be wrapped in parentheses when defining a parameterized macro like
square(x)? - What is the primary advantage of using a macro over a function for a simple operation like squaring a number?
- How could you use
#define DEBUGand#ifdef DEBUG ... #endifto add debugging output that can be easily disabled? - What does the
#undefdirective do, and why is it used?
π Lecture 25 β Default Function Arguments, Inline Functions, and Function Overloading
π Overview: This lecture marks the transition from traditional C programming to C++ features. It covers essential C++ enhancements including default function arguments, flexible variable declaration placement, inline functions as safer alternatives to macros, and function overloading for cleaner, more readable code. These concepts form the foundation for understanding object-oriented programming later.
ποΈ Topics Covered
The lecture begins with a brief history of programming languages from machine language to C++. It then covers structured programming principles and their limitations, leading to the introduction of C++ features. Core topics include default function arguments with their right-to-left placement rules, flexible variable declaration placement, inline functions versus macros with side-effect analysis, and function overloading based on parameter type and number.
π Lecture Summary
History of C/C++
C was developed by Bell Labs scientists in the 1970s as a lean, powerful language. Major operating systems like Unix were written in C. The evolution of programming languages went from machine language (0s and 1s) to assembly language with symbolic codes, then to high-level languages like COBOL and FORTRAN. These high-level languages led to "spaghetti code" where programs were unstructured with branches growing in every direction, making them difficult to read and manage.
Structured Programming
In structured programming, problems are broken into smaller pieces or modules, each corresponding to a function. This is the top-down structured programming approach. Key rules include: Divide and Conquer β functions should not be longer than 2-3 pages/screens; Single Entry Single Exit rule inside functions for readability and manageability; and well-commented programs explaining what a function does, its parameters, and what it returns.
Limitations of Structured Programming
In functional programming, data exists outside the program and functions process that data. As problems became complex, developers realized data cannot remain outside β it should be part of the program. This led to data-driven programming where data comes first, then functions operate on it. This originated Object Oriented Programming. In the early 1980s, Bjarne Stroustrup at Bell Labs enhanced C to overcome these shortcomings, first called C with Classes, eventually named C++.
Default Function Arguments
When certain parameters of a function are passed the same value most of the time, default function arguments can be used. The default value is provided inside the function prototype or definition.
π Definition β Default Function Arguments: Parameters that take default values when no argument is provided for them during the function call.
void f(int i = 1, double x = 10.5)
{
cout << "The value of i is: " << i;
cout << "The value of x is: " << x;
}
Calling f(); assigns default values: i=1, x=10.5. Calling f(2); assigns i=2, x=10.5 (default). Calling f(1, 2); assigns i=1, x=2.
π Rule: Arguments are assigned to parameters from left to right. Parameters with default values must be placed on the extreme right of the parameter list. You cannot skip the first parameter with a default value and provide a value for the second.
Example of Default Function Arguments
#include <iostream.h>
void show(int = 1, float = 2.3, long = 4);
main()
{
show(); // All three arguments default
show(5); // Provide 1st argument
show(6, 7.8); // Provide 1st and 2nd
show(9, 10.11, 12L); // Provide all three arguments
}
π Output:
first = 1, second = 2.3, third = 4
first = 5, second = 2.3, third = 4
first = 6, second = 7.8, third = 4
first = 9, second = 10.11, third = 12
Placement of Variable Declarations
In C++, variables can be declared anywhere in a function, not just at the top. The philosophy is to declare variables just before they are actually used, increasing code readability. A variable declared inside a code block is visible only within that block.
for(int i = 0; condition; increment)
{
// i visible here
}
i = 500; // Valid - i declared outside the for loop's braces
Example of Placement of Variable Declarations
#include <iostream.h>
main()
{
for(int lineno = 0; lineno < 3; lineno++)
{
int temp = 22;
cout << "\nThis is line number " << lineno
<< " and temp is " << temp;
}
if(lineno == 4) // lineno still accessible
cout << "\nOops";
// Cannot access temp
}
π Output:
This is line number 0 and temp is 22
This is line number 1 and temp is 22
This is line number 2 and temp is 22
Inline Functions
Inline functions are declared using the inline keyword before the function name. This is a directive to the compiler to insert the full function definition at each call location, eliminating function call overhead (loading parameters onto the stack).
π Definition β Inline Function: A function that is expanded at the point of call, avoiding the overhead of a function call. The inline keyword is only a suggestion to the compiler β large functions are not expanded inline even if declared inline.
Disadvantages: If called 100 times and the function is 10 lines long, program size increases by 1000 lines. The compiler may reject the inline request.
Advantages over macros: Inline functions perform automatic type checking on parameters and have no side effects. Macros can cause unexpected behavior due to multiple parameter evaluation.
Macro example with side effect:
#define MAX(A, B) ((A) > (B) ? (A) : (B))
i = MAX(x++, y++); // Larger value incremented TWICE
Inline function (no side effect):
inline int max(int a, int b) {
if(a > b) return a;
return b;
}
i = max(x++, y++); // Works as expected - each variable incremented once
π Output comparison:
Macro: x = 24, y = 47 (y incremented twice)
Inline: x = 24, y = 46 (y incremented once, as expected)
π‘ Why this matters: Macros can produce subtle bugs when parameters have side effects (like increment operators). Inline functions are safer and should be preferred.
Function Overloading
Function overloading means using the same function name to perform different tasks depending on the situation. The << operator with cout is overloaded for many data types (int, double, float, string) β this is possible because the header file iostream.h contains prototypes for all those functions.
π Definition β Function Overloading: Using the same function name to perform multiple tasks depending on the type and number of arguments passed.
Overloaded functions are differentiated by:
- Type of arguments
- Number of arguments
NOT by return type β you cannot have:
int f(int);
double f(int); // Error: ambiguous declarations
// Overloaded print functions
void print(int i) {
cout << "\nThe value of the integer is: " << i;
}
void print(double d) {
cout << "\nThe value of the double is: " << d;
}
void print(char* s) {
cout << "\nThe value of the string is: " << s;
}
π Output:
The value of the integer is: 100
The value of the double is: 123.12
The value of the string is: This is a test string
The compiler uses a technique called name mangling to generate a unique token for each overloaded function based on its name and parameters.
Example of Function Overloading
inline void stringCopy(char *dest, const char *src) {
strcpy(dest, src);
}
inline void stringCopy(char *dest, const char *src, int len) {
strncpy(dest, src, len);
}
β Key Takeaways
Four critical C++ features were introduced in this lecture. First, default function arguments allow parameters to have predefined values, with the rule that parameters having defaults must be on the extreme right of the parameter list. Second, variable declarations can be placed anywhere in C++, not just at the top of blocks, improving readability. Third, inline functions should be preferred over macros because they provide type checking and avoid side effects from multiple parameter evaluations. Fourth, function overloading enables multiple functions with the same name but different parameter types and/or counts, improving code readability β but overloading based only on return type is not allowed.
π§ Quick Revision Questions
- What is the rule for placing default argument parameters in a function parameter list, and why?
- What is the difference between a macro
#define MAX(A,B)and an inline functioninline int max(int a, int b)regarding side effects? - Can you overload functions based only on return type? Why or why not?
- In the code
for(int i=0; i<10; i++), is the variableiaccessible after the for loop? Explain. - What is name mangling and why is it necessary for function overloading?
π Lecture 26 β Classes and Objects
π Overview: This lecture introduces the fundamental concepts of classes and objects in C++. It explains how classes extend the language by creating user-defined data types that encapsulate both data and functions, and emphasizes the critical importance of separating interface from implementation for robust, maintainable code.
ποΈ Topics Covered
The lecture covers the definition and structure of classes, the difference between structs and classes regarding visibility, the use of private and public access specifiers to achieve encapsulation, the separation of interface from implementation, how to define member functions using the scope resolution operator, and the concept of constructors including default constructors and constructors with default arguments.
π Lecture Summary
Classes and Objects
In todayβs lecture, we begin learning about classes and objects. A class is very closely related to a struct, but unlike a struct which groups only data variables, a class groups both data variables and the functions that manipulate that data.
π Definition β Class: A user-defined data type that includes both data members and member functions to manipulate that data.
These functions are called member functions or methods. When we create variables of a class, they are given a special name.
π Definition β Object: An instance of a class.
π‘ Why this matters: Just as int i; creates an instance of the built-in type int, Date myDate; creates an instance (object) of the user-defined class Date.
Definition of a class
The structure of a class uses the class keyword, followed by the class name and braces enclosing the definition.
class name_of_class{
// definition of class
};
Consider a Date class:
class Date{
int Day;
int month;
int year;
};
An object is created as Date myDate;.
Separation of Interface from the Implementation
The key difference between a struct and a class is the visibility of data members. In a struct, data is open and visible to every part of the program, which can lead to problems β for example, a variable storing a tax rate could accidentally be changed by a loop.
π Definition β Encapsulation: The concept of hiding data so that it cannot be directly accessed but can still be used through a controlled interface.
The real-world example of a wristwatch illustrates this: we see the hands but cannot touch them; we use a button to adjust the time. The internal mechanism is hidden (implementation), while the button is the interface.
Structure of a class
The default visibility of all data members and member functions of a class is hidden and private.
π Definition β private: A keyword that makes data members and member functions accessible only within the class itself, not from outside.
π Definition β public: A keyword that makes data members and member functions visible and accessible from outside the class.
class Date
{
private:
// private data and functions
public:
// public data and functions
};
Normally, data is kept private, and member functions (which manipulate the data) are kept public. These public functions form the interface of the class. Member functions can see and manipulate the private data members because they are part of the class.
For example, to set the month, we cannot write myDate.month = 10; because month is private. Instead, we write a public function:
void setMonth(int month);
And call it as:
myDate.setMonth(10);
π‘ Why this matters: In a struct, we could write myDate.month=13; creating an invalid date. With a class, we can validate data inside the setMonth function. The public part becomes the interface β what we want to show β while the private part is the implementation β what we want to hide.
This separation allows the implementation to change completely while the interface remains the same, just as a car's steering (interface) has remained the same even as the internal steering mechanism evolved from rods to microprocessors.
Sample program: Date class in detail
Here is the complete Date class implementation:
class Date{
public:
void display();
Date(int, int, int);
private:
int day, month, year;
};
π Definition β Scope Resolution Operator (::): A double colon used to define a member function outside the class, telling the compiler which class the function belongs to.
Example of defining a member function:
Date::display()
{
cout << "The date is " << day << "-" << month << "-" << year << endl;
}
The functions are called by objects, not by the class. date1.setMonth(12) manipulates the data of date1, while date2.setMonth(12) manipulates the data of date2.
Setter and getter functions become the public interface:
- setDay(int), setMonth(int), setYear(int) β to set values
- getDay(), getMonth(), getYear() β to retrieve values
Output of the program:
The date is 1-1-2000
The date is 10-12-2002
Constructors
π Definition β Constructor: A special member function with the same name as the class, having no return type, that is automatically called when an object is created. It initializes the object into a consistent and valid state.
If no constructor is written, C++ provides a default constructor that takes no arguments.
Example of a constructor definition:
Date::Date(int theDay, int theMonth, int theYear)
{
day = theDay;
month = theMonth;
year = theYear;
}
Object creation with initialization:
Date myDate(1, 1, 2003);
This creates the object AND initializes day=1, month=1, year=2003.
π Example: Without a custom constructor, Date myDate; creates an object with uninitialized data members. The default constructor does not set any values.
Default arguments with constructors
Constructors can use default arguments, providing flexibility in object creation.
Date::Date(int theDay, int theMonth, int theYear = 2002)
{
day = theDay;
month = theMonth;
year = theYear;
}
Now objects can be created in multiple ways:
Date myDate; // Default constructor - uninitialized
Date myDate(1, 1, 2000); // All three arguments provided
Date myDate(1, 1); // Uses default value for year (2002)
Constructors can be overloaded β multiple constructors with different parameters. For example, one constructor could take three integers, while another takes a character string like "01-Jan-2003" and parses it.
Output from the program with constructors:
The date is 1-1-1900
The date is 1-1-2000
The date is 10-12-2002
β Key Takeaways
A class is a user-defined data type that bundles both data members and member functions. The default visibility of class members is private, making data hidden and accessible only through public member functions, which form the class's interface. This separation of interface from implementation allows internal logic to change without affecting external code. Constructors are special functions that initialize objects automatically upon creation, and they can be overloaded or given default arguments for flexible object creation. The scope resolution operator (::) is essential for defining member functions outside the class definition.
π§ Quick Revision Questions
- What is the difference between a struct and a class regarding default visibility of members?
- What does it mean to separate interface from implementation, and why is this important?
- How do you define a member function outside the class, and what operator is used?
- What is a constructor, and when is it automatically called?
- How can you create an object using default arguments in a constructor? Give an example.
π Lecture 27 β Classes and Objects, Constructors, Types of Constructors, Utility Functions, Destructors
π Overview: This lecture builds on the foundational concepts of classes and objects in object-oriented programming. It introduces constructors for initializing objects, explains different types including default, parameterized, and overloaded constructors, discusses utility functions as private helpers, and covers destructors for cleanup. Understanding these mechanisms is essential for writing robust, well-structured C++ programs.
ποΈ Topics Covered
This lecture covers Classes and Objects in depth, moving from function-oriented to object-oriented thinking. It explains that a class is a user-defined data type with data members and member functions, with data hiding via encapsulation. It details Constructors as special functions for initialization, including compiler-generated, simple, parameterized, and overloaded constructors. It also introduces Utility Functions (private member functions used internally) and Destructors, which are automatically called when an object is destroyed, primarily for memory deallocation.
π Lecture Summary
Classes and Objects
This lecture is a sequel of the previous discussion on 'Classes' and 'Objects'. The use of 'classes and objects' has changed our way of thinking. Instead of having function-oriented programs (getting data and performing functions with it), we now have data that knows how to manipulate itselfβthis is object-oriented programming. Our programs revolve around data and objects.
In real-world programming, we deal with real-world entities like cycles, cars, buildings, and people, which we perceive as objects. Each object has a behavior (functions or methods) and attributes (data members). For example, a man has attributes like height and weight, and actions like talk, walk, sit, and stand. An aeroplane has attributes like height, width, and number of seats, and actions like takeoff, flying, and landing. In programming terms, attributes are data members, and actions are functions or methods.
Data now encompasses more than just numbers and lettersβit includes pictures, images, windows, dialogue boxes, audio, and video (multimedia). With this expanded scope, we can think of an integer that knows how to display itself, or an audio object that knows how to play itself.
Class
A class is a way of defining a user-defined data type. It contains data members and functions that manipulate that data. Encapsulation (data hiding) means that the data of a class cannot be accessed from outside, except through defined member functions. To hide data, we declare it private, making it available only to member functions of the class (except friend functions). A class is divided into the private part (implementation) and the public part (interface).
The analogy of a room with a curtain illustrates this: things behind the curtain (private) are visible only to insiders, while outsiders see only what is in front of the curtain (public interface). A function inside the class (member function) can access and manipulate all things in the class. A function outside the class can only access the public interface. A constructor must be in the public section of the class so it can be called from outside.
Constructors
A constructor is a special function called whenever we instantiate (create) an object of a class. If we do not define a constructor, C++ provides a default constructor that does nothing. Constructors were introduced because the majority of programming bugs (logical errors) occur due to uninitialized data. Using an uninitialized variable like int i; and then j = 2 * i; causes difficult-to-find logical errors. Constructors give us an opportunity to initialize data members so that when a program gets an object, the data is in a known, valid state. A class is a user-defined data type and does not take space in memory until we create an object from it. Constructors create space for data members and put values in them.
Key characteristics of constructors:
- A constructor is a function that has the same name as the class.
- It has no return type, so it contains no return statement.
- Whenever an instance of a class comes into scope, the constructor is executed.
- Constructors can be overloaded.
Types of Constructors
Compiler Generated Constructor If a constructor is not defined by the user, the compiler generates it automatically. This constructor has no parameter and does nothing. The behavior of the compiler-synthesized constructor is rarely what we wantβit does no initialization.
Simple Constructor A simple constructor is a user-defined constructor that takes no argument. When written, it assumes the role of the default constructor, and the compiler will not call its own default constructor. It is good programming practice to always provide a default constructor (a constructor with no arguments).
Parameterized Constructors
A parameterized constructor takes arguments. It is automatically called when the required number of arguments are passed to it. Through this, we can easily assign passed values to class data members for a particular object. For example: Date (int, int, int);βa parameterized constructor taking three integer arguments.
Constructor Overloading We can provide more than one constructor using function overloading. The rules for function overloading apply: the function name remains the same, but the argument list must differ in number or type of arguments. We cannot have two functions with the same number and type of arguments. The same concept applies to constructors.
Default Arguments in Constructors
In C++, we can provide default arguments to constructors. For example: Date (int day=1, int month=1, int year=1);. If we provide default values for all arguments, this constructor becomes the default constructor for the class. It is better not to write a separate constructor with no arguments in this case.
π‘ Why this matters: Constructors ensure that every object starts in a valid state, preventing the common and hard-to-debug errors caused by uninitialized data.
Example of Constructors:
Consider a Date class with data members day, month, and year (all int). The constructor can initialize these to a known state, such as day=1, month=1, year=1900. We can write a constructor that takes three arguments (int day, int month, int year) and assigns them to the data members. When we write Date myDate;, space for myDate is reserved in memory, then control goes to the constructor which assigns values to the private data members.
π Example of Constructor Overloading:
class Date {
public:
Date(); // default constructor
Date(int, int); // two-argument constructor
Date(int, int, int); // three-argument constructor
private:
int day, month, year;
};
When creating objects: Date date1; calls the default constructor, Date date2(12,12); calls the two-argument constructor, and Date date3(25,12,2002); calls the three-argument constructor.
Utility Functions
While member functions are normally in the public part of a class, some functions are private and are called utility functions. These are used by other methods of the class but are not meant to be accessed from outside. For example, a setDate function might be called by the constructor and by other member functions, but we may not want it called directly from outside the class. Utility functions are placed in the private section of the class.
Destructors
A destructor has the same name as the class with a preceding tilde (~), written as a single word (e.g., ~Date). The destructor cannot be overloadedβthere is only one destructor per class. It is automatically called when an object is destroyed. An object is destroyed when it goes out of scope (e.g., when a function exits or the main program ends).
The destructor is normally used for memory manipulation purposes. If a constructor allocates memory (e.g., from the heap/free store), the destructor must de-allocate that memory to ensure it is returned to the free store.
Key characteristics of destructors:
- Destructors cannot be overloaded.
- Destructors take no arguments.
- Destructors don't return a value, so they have no return type and no return statement in the body.
Complete Example with Date Class:
The lecture provides a complete program showing constructors, destructor, and set/get functions. The class has three overloaded constructors (default, two-argument, three-argument) and a destructor. Each constructor displays a message when called ("The default constructor is called", etc.), and the destructor displays "The object has destroyed". The program creates three objects and demonstrates when each constructor is called based on the arguments provided.
Memory Management:
When objects of a class are created, the functions of the class take only one copy in memory, shared by all objects. However, the data part of each object takes individual memory locations. When we call a function on a specific object using the dot operator (.), the function operates only on that object's data. For example, date1.setMonth(3); sets only the month of date1, leaving date2 and date3 untouched.
π Definition β Constructor: A special function with the same name as the class, having no return type, that is automatically called when an object is instantiated to initialize its data members.
π Definition β Destructor: A special function with the same name as the class preceded by a tilde (~), taking no arguments and having no return type, automatically called when an object is destroyed, typically used for memory cleanup.
π Formula:
- Constructor syntax:
ClassName(parameters);β No return type, same name as class. - Destructor syntax:
~ClassName();β No return type, no parameters, cannot be overloaded.
π Example:
class Date {
public:
Date(); // Default constructor
Date(int, int, int); // Parameterized constructor
~Date(); // Destructor
void setDay(int i); // Set function
int getDay(); // Get function
private:
int day, month, year; // Private data members
};
// Constructor with three arguments
Date::Date(int theDay, int theMonth, int theYear) {
day = theDay;
month = theMonth;
year = theYear;
cout << "The constructor with three arguments is called" << endl;
}
// Destructor
Date::~Date() {
cout << "The object has destroyed" << endl;
}
int main() {
Date date1, date3(25,12,2002); // Objects created
// Output: The default constructor is called
// The constructor with three arguments is called
// The object has destroyed (twice, when main ends)
}
β Key Takeaways
Constructors are essential for object initialization, preventing uninitialized data errors by ensuring objects start in a known valid state. They share the class name, have no return type, and can be overloaded with different parameter lists. Destructors, named with a tilde prefix, cannot be overloaded and are used for cleanup, especially deallocating dynamically allocated memory. Utility functions (private member functions) support internal class operations without exposing them to outside code. All objects of a class share a single copy of member functions in memory, while each object has its own data space, with the dot operator ensuring functions operate on the correct object's data.
π§ Quick Revision Questions
- What is the main purpose of a constructor in C++, and what problem does it solve?
- What are the three types of constructors discussed in this lecture, and how do they differ?
- Why can't a constructor have a return type, and what happens if you include a return statement in its body?
- What is a utility function, and where is it placed within a class?
- When is a destructor called, and why can it not be overloaded?
π Lecture 28 β Dynamic Memory Management with Classes in C++
π Overview: This lecture explores dynamic memory allocation in C++ using the
newanddeleteoperators, contrasting them with C'smalloc()andfree()functions. It explains how these operators integrate with classes, constructors, and destructors, and covers practical considerations for managing memory in object-oriented programs.
ποΈ Topics Covered
The lecture begins by reviewing C-style memory allocation with malloc(), calloc(), and free(), then introduces C++'s new and delete operators for simpler, type-safe allocation. It demonstrates using new with classes and objects, explains how constructors are called automatically during allocation, and shows the proper use of destructors for deallocation. Memory leak prevention, class abstraction, messaging between objects, and language extension through user-defined types round out the discussion.
π Lecture Summary
Memory Allocation in C
In C, memory is dynamically allocated at runtime from a region called the heap using functions like malloc(), calloc(), and realloc(). The malloc() function requires the programmer to specify the exact number of bytes needed and returns a void pointer (void *), which must be cast to the appropriate type before use. For example: datePtr = (Date *) malloc( sizeof( Date ) );. This memory is uninitialized and may contain garbage values. Memory must be freed using the free() function.
π Definition β heap: The region of memory allocated at runtime in C. In C++, this region is called the free store.
π Example: To allocate space for 10 integers in C: malloc( 10 * sizeof(int) ); β This returns a void * that must be cast to int *.
Memory Allocation in C++
C++ introduces the new operator for dynamic memory allocation. Unlike malloc(), new is an operator, not a function. It automatically determines the number of bytes needed, returns a pointer of the correct type (no casting required), and initializes the memory. The corresponding deallocation operator is delete.
π Definition β free store: The region of available memory in C++ from which dynamic allocation occurs (equivalent to the heap in C).
π Formula: pointer = new data_type; β allocates memory for one variable of data_type
π Formula: pointer = new data_type[number_of_elements]; β allocates an array
π Formula: delete pointer; β deallocates a single object
π Formula: delete [] pointer; β deallocates an array
π Example:
int *iptr;
iptr = new int; // allocates one int, returns int*
iptr = new int[10]; // allocates array of 10 ints
delete [] iptr; // deallocates the array
π‘ Why this matters: The new operator is safer and simpler than malloc() because it eliminates the need for sizeof(), explicit casting, and manual byte calculations.
When memory in the free store is insufficient, malloc() returns NULL, while the new operator returns 0. Always check the return value of new against 0 for failure.
new Operator and Classes
The new operator works with user-defined class types exactly as with primitive types. When creating an object with new, three actions occur automatically:
- It determines the memory size needed for the object (no
sizeofneeded) - It calls the constructor of the class to initialize data members
- It returns a pointer of the class type (no casting needed)
π Definition β constructor call on new: When new creates an object, the class constructor is invoked automatically to initialize the object with meaningful values rather than garbage.
π Example:
Date *dptr;
dptr = new Date; // allocates memory AND calls Date() constructor
int day = dptr->getDay(); // access via arrow operator
For an array of objects: dptr = new Date[10]; β This calls the default (parameterless) constructor for each of the 10 objects and returns a pointer to the first object.
π‘ Why this matters: Unlike malloc(), which only allocates raw bytes, new creates a properly initialized object by invoking its constructor.
Classes and Structures in C++
In C++, structures and classes are very similar. Both can contain data members and member functions. The key difference is default visibility: members of a struct are public by default, while members of a class are private by default. Good practice is to explicitly write public: or private: keywords for clarity.
π Example:
struct abc { // members are public by default
int integer;
float floatingpoint;
};
class Date { // members are private by default
public:
// public interface
private:
int month, day, year;
};
new Operator and Constructors
The new operator can be called from inside a constructor to dynamically allocate memory for data members. This is common when a class has a pointer data member whose size varies at runtime, such as a student's name.
π Definition β dynamic allocation in constructor: Using new within a constructor to allocate memory for pointer data members whose size is determined at runtime.
π Example: In a Student class, the constructor allocates memory for the name string: this->name = new char[strlen(name) + 1]; followed by strcpy(this->name, name);
delete Operator and Classes
When memory is allocated with new inside a constructor, it must be freed with delete inside the destructor. The destructor is the appropriate place because it is called when the object is destroyed. Memory allocated from the free store is a system resource that is NOT automatically returned to the system β it must be explicitly freed.
π Rule of thumb: Whenever a class has a pointer data member that allocates memory at runtime, provide a destructor to release that memory.
π Example β Complete allocation/deallocation cycle:
class MyDate {
public:
MyDate() { month = day = year = 0; }
~MyDate() { /* cleanup code */ }
private:
int month, day, year;
};
main() {
MyDate *dptr = new MyDate[10]; // allocate 10 objects, constructors called
delete [] dptr; // destructors called, memory freed
}
π‘ Why this matters: Without proper deallocation in the destructor, memory leaks occur β allocated memory is never returned to the system even after program termination.
The output from proper code shows constructors called 10 times (for allocation) and destructors called 10 times (for deallocation), with no memory leak.
new, delete outside Constructors and Destructors
The new and delete operators can be called from any function, not just constructors and destructors. For example, you might need to resize a dynamically allocated string within an existing object by first using delete to free the old memory, then new to allocate new space.
π Example: Changing a student's name from "Abdul Khaliq" to "Abdul Khaliq Khan" requires: deallocating the old string with delete[], calculating the new string length with strlen(), allocating new memory with new[], and copying the new string.
main() Function and Classes
In C++ programs using classes, the main() function becomes very small β often containing only a few lines to create objects and call methods. Approximately 90% of program code resides inside class definitions. Classes are written first, and main() is written after class definitions.
Class Abstraction
Abstraction means exposing only the interface (method signatures and their purposes) to users while hiding the implementation details (internal variables, data manipulation, function internals). Users only need to know what a method does, not how it does it.
π Definition β class abstraction: The principle of providing only the public interface to users while keeping implementation details private and hidden.
Messages and Methods
Calling a function on an object is equivalent to sending a message to that object. The term "method" comes from the idea that it is a "way of doing something." The entire program operates by sending messages between objects and receiving responses.
π Definition β messaging: The object-oriented concept where function calls to objects are viewed as sending messages, requesting the object to perform some action.
Classes to Extend the Language
C++ allows programmers to create user-defined data types (classes) that extend the language's capabilities. For example, since C++ has no primitive type for complex numbers, a Complex class can be created with double members for real and imaginary parts. Operators like +, *, and / can be overloaded to work naturally with complex numbers.
π Example: Without operator overloading, adding complex numbers requires a function like cadd(a, b). With operator overloading, you can write a + b naturally for user-defined complex types.
β Key Takeaways
The new operator in C++ is superior to malloc() because it automatically determines memory size, calls constructors for proper initialization, and returns the correct pointer type without casting. Every new must be paired with a matching delete to prevent memory leaks β typically using constructors for allocation and destructors for deallocation. When allocating arrays with new[], use delete[] with brackets. The free store memory is a system resource that requires explicit deallocation. Classes enable abstraction by exposing interfaces while hiding implementation, and they allow programmers to extend the C++ language with new data types like complex numbers.
π§ Quick Revision Questions
- What are the three key advantages of the
newoperator overmalloc()when creating class objects? - Why must destructors be provided for classes that have pointer data members allocated with
new? - What is the correct syntax for allocating and deallocating an array of 10
Dateobjects? - What does
newreturn if memory in the free store is insufficient? - How does class abstraction benefit both the programmer and the user of a class?