π Lecture 36 β Stream Manipulations
π Overview: This lecture explores how to control and format input/output streams in C++. It covers the different types of manipulators, format state flags, and various formatting techniques that allow programmers to control how data is displayed, including base conversion, field width, precision, and alignment.
ποΈ Topics Covered
The lecture covers stream manipulations including state-checking with flags (eof, fail, bad, good), non-parameterized manipulators (dec, hex, oct, endl, ends, flush, ws), parameterized manipulators (setw, setfill, setprecision, setbase), format state flags for controlling output behavior, formatting manipulation for justification, showing the base of numbers, scientific representation, and uppercase/lowercase control.
π Lecture Summary
Stream Manipulations
To use stream manipulations in C++, we need to include the iomanip.h header file (in addition to iostream.h and fstream.h). Stream objects have internal flags that can be used to check the state of the stream. These flags can be thought of as integers where each bit position specifies a particular state. For example, cin.eof() returns the state of the end-of-file bit. Similarly, cin.fail() checks if an operation has failed due to a formatting error, and cin.bad() checks if data has been lost during I/O. The cin.good() bit is set when both fail and bad bits are not set. To reset these bits to their normal good state, we use the cin.clear() member function.
Manipulators
Manipulators are inserted into streams to change their behavior. They can be either non-parameterized (taking no arguments) or parameterized (taking arguments). For example, endl is a non-parameterized manipulator that outputs a new line and flushes the buffer. Flush is another manipulator that flushes the output buffer. Manipulators allow us to perform various formatting tasks such as printing a floating-point number with a specific number of decimal places or filling empty spaces with special characters (like asterisks on cheques to prevent tampering).
π‘ Why this matters: Manipulators provide an intuitive, stream-based way to control formatting without complex function calls.
Non-Parameterized Manipulators
Non-parameterized manipulators are simple manipulators that take no arguments. The most important ones for number representation convert between different bases (number systems). The oct manipulator converts numbers to octal (base 8), hex converts to hexadecimal (base 16), and dec converts back to decimal (base 10). For example, cout << oct << i displays the octal value of integer i. These manipulators work with both cin and cout. The ws manipulator skips leading whitespace. Other non-parameterized manipulators include endl (new line and flush), ends (terminate string with NULL), and flush (flush the stream).
π Definition β Base: The number system used to represent numbers (binary=2, octal=8, decimal=10, hexadecimal=16).
π Formula: 2^n - 1 β The maximum value that can be stored in n bits
π‘ Why this matters: Different bases map directly to bit patterns - octal maps to 3 bits, hexadecimal maps to 4 bits, making them useful for low-level programming and hardware interaction.
Parameterized Manipulators
Parameterized manipulators take arguments to control formatting. The setw (set width) manipulator takes an integer argument specifying the field width in spaces. For example, cout << setw(4) << number prints the number in a space of 4 digits with right justification by default. The setfill manipulator takes a character argument to fill empty spaces. When combined with setw, it fills the unused space: cout << setfill('*') << setw(10) << amount prints the amount in 10 spaces with asterisks filling the empty positions. These manipulators can be cascaded because the stream insertion operator (<<) returns a reference to the cout object. The setprecision manipulator takes an integer argument to control the number of decimal places displayed for floating-point numbers: cout << setprecision(2) << pi prints pi (3.1415926) as 3.14. The setbase manipulator takes the base as an argument (0, 8, 10, or 16) and is an alternative to oct, dec, and hex: cout << setbase(8) << number is equivalent to cout << oct << number.
π Definition β setw: Sets the minimum field width for the next output operation only π Example: cout << setw(10) << amount β Prints amount right-justified in 10 spaces π Example: cout << setfill('*') << setw(10) << 4000 β Outputs ******4000
π‘ Why this matters: setfill prevents fraud on printed cheques by filling empty spaces with characters that cannot be overwritten.
Format State Flags
Format state flags are a set of flags that control input/output behavior through the flags, setf, and unsetf member functions. These flags are defined in the ios class and include options like ios::skipws (skip whitespace), ios::left (left justify), ios::right (right justify), ios::internal (padding between sign and number), ios::dec/oct/hex (base conversion), ios::showbase (display base notation), ios::showpoint (show decimal point), ios::uppercase (use uppercase letters), ios::showpos (show + sign for positives), ios::scientific (scientific notation), and ios::fixed (fixed-point notation).
As alternatives to manipulators, there are member functions that perform the same tasks. For example, cout.width(10) is equivalent to cout << setw(10), cout.precision(2) is equivalent to cout << setprecision(2), and cout.fill('*') is equivalent to cout << setfill('*'). Member functions are defined in iostream.h, while manipulators require iomanip.h. An important distinction is that inline manipulators like setw apply only to the very next piece of data, not to subsequent output operations.
π‘ Why this matters: Multiple ways exist to accomplish the same formatting task, giving programmers flexibility in coding style.
Formatting Manipulation
The setf member function allows us to set format state flags for controlling output justification: cout.setf(ios::flag, ios::adjustfield). The adjustfield has values ios::left (left-justify), ios::right (right-justify), ios::internal (padding between sign and number), and ios::left | ios::right (center output). For example:
cout.setf(ios::left, ios::adjustfield);
cout << "|" << setw(12) << i << "|" << endl; // outputs |-1234 |
cout.setf(ios::right, ios::adjustfield);
cout << "|" << setw(12) << i << "|" << endl; // outputs | -1234|
cout.setf(ios::internal, ios::adjustfield);
cout << "|" << setw(12) << i << "|" << endl; // outputs |- 1234|
Showing the Base
The showbase flag, when set, displays numbers with special notations indicating their base. Using cout.setf(ios::showbase) followed by setting the basefield, numbers are displayed with prefixes: octal numbers get a leading 0, hexadecimal numbers get a leading 0x, and decimal numbers are displayed as usual. For example, the number 77 displayed in octal becomes 0115 (with leading 0), in hexadecimal becomes 0x4d (with 0x prefix), and in decimal remains 77.
π Example: cout.setf(ios::oct, ios::basefield) β Displays 77 as 0115
Scientific Representation
The ios::scientific flag sets the output stream to display floating-point numbers in scientific notation (e.g., 1.946000e+009). To restore default notation, use ios::fixed: cout.setf(ios::fixed, ios::floatfield). The ios::uppercase flag controls case: when set, the 'e' in scientific notation becomes uppercase 'E', and hexadecimal letters (A-F) are displayed in uppercase.
β Key Takeaways
There are two types of manipulators: non-parameterized (oct, hex, dec, endl, ws) and parameterized (setw, setfill, setprecision, setbase). The setw manipulator applies only to the next output operation, while setfill and setprecision persist until changed. Format state flags (ios::left, ios::right, ios::internal, ios::scientific, ios::showbase) provide an alternative way to control formatting through the setf member function. Member functions (width, precision, fill) offer yet another approach to accomplish the same tasks as manipulators. The showbase flag adds prefixes (0 for octal, 0x for hexadecimal) to help identify the base of displayed numbers.
π§ Quick Revision Questions
- What header file must be included to use parameterized manipulators like setw and setprecision?
- Explain the difference between setw and setfill - which one applies only to the next output operation?
- What is the output of
cout << oct << 10and why? - How would you display the number -1234 with the minus sign left-justified and the digits right-justified in a field of 12 spaces?
- What prefix is added to a hexadecimal number when the showbase flag is set?
π Lecture 37 β Overloading Insertion and Extraction Operators
π Overview: This lecture explains how to overload the stream insertion (
<<) and extraction (>>) operators for user-defined classes. It covers why these operators must be implemented as non-member functions, how to declare them as friends of a class, and how to return references to support cascading operations, with practical examples using aDateclass and aMatrixclass.
ποΈ Topics Covered
The lecture begins by reviewing operator overloading principles (preserving operator spirit and number of operands) and the need to support cascading. It then explains why stream insertion and extraction operators cannot be member functions and must be non-member friends. The return types (ostream& and istream&) and parameter passing (first parameter always by reference, second parameter by reference for extraction) are detailed. Two full examples are provided: a Date class and a Matrix class, both with overloaded << and >>. The lecture concludes with practical tips for implementing these operators.
π Lecture Summary
Overloading Insertion and Extraction Operators
When overloading operators, the spirit or behavior of the original operator must be maintained. For stream insertion (<<) and extraction (>>), this means preserving their ability to work with streams like cin and cout. The number of operands cannot be changed: << and >> are binary operators, so they take two operands.
π Definition β Binary operator: An operator that takes two operands. For << and >>, the left operand is the stream object (e.g., cin, cout) and the right operand is the object being inserted or extracted.
The return type of an overloaded operator must support cascading. For example, a + b + c works because each + returns a value. Similarly, cout << a << b works if << returns a reference to ostream.
π Definition β Cascading: The ability to chain multiple uses of an operator in a single expression, e.g., cin >> a >> b or cout << x << y.
The iostream.h file already contains declarations for overloaded << and >> for native data types like int, double, float, char, etc. To use these operators with user-defined classes, we must overload them ourselves.
Stream insertion (<<) and extraction (>>) operators cannot be overloaded as member functions. The reason is that for member operators, the driving object is on the left side of the operator. For these operators, the left side is always a stream object (cin or cout), not an object of our class. Therefore, they must be overloaded as non-member functions.
To access private members of the class from these non-member functions, we can either use the class's public setters and getters (if available) or declare the operator function as a friend of the class. We can only declare friends for our own classes, not for library classes like istream or ostream.
The general prototype for the stream insertion operator is:
ostream & operator << (ostream & output, Vehicle v);
Here, cout is replaced by the reference output. The first parameter must be passed by reference; the compiler does not allow passing it by value. This is because objects passed by value are local to the function and destroyed when the function returns, making it meaningless to return a reference to them. The function returns a reference to ostream to support cascading.
π‘ Why this matters: Passing by reference avoids copying the stream object, which is often large, and ensures that the return value remains valid for chaining.
When the operator is declared as a friend of the class, it can directly access private members. For example, if tyre is a private int member of Vehicle, inside the operator function we can write:
output << v.tyre; // This is equivalent to cout << v.tyre
Since tyre is a native type, the built-in << for int handles the output. We are building complex operations on top of already available functionality for native types.
π Formula: Overloaded << return type: ostream& β returns a reference to the output stream to allow cascading.
π Example (Date class, overloaded <<):
class Date {
friend ostream& operator << (ostream & os, Date d);
// ...
};
ostream & operator << (ostream & os, Date d) {
os << d.day << "." << d.month << "." << d.year; // access private data as friend
return os;
}
For the stream extraction operator (>>), the rules are similar: it cannot be a member function, must be a non-member (usually a friend), returns istream&, and accepts the first parameter as istream&. An additional restriction is that the second parameter must also be passed by reference because the operator modifies that object (it reads values into it).
π Definition β Stream extraction operator (>>): An operator that extracts (reads) data from an input stream (like cin) and stores it in a variable or object.
π Formula: Overloaded >> prototype: istream & operator >> (istream & input, ClassName & obj);
π Example (Date class, overloaded >>):
class Date {
// ...
friend istream & operator >> (istream & is, Date & d);
};
istream & operator >> (istream & is, Date& d) {
cout << "\n\n Enter day of the date: ";
cin >> d.day;
cout << " Enter month of the date: ";
cin >> d.month;
cout << " Enter year of the date: ";
cin >> d.year;
return is;
}
Note: For <<, the second parameter can optionally be passed by reference for performance, but it is not mandatory. For >>, it is mandatory.
Example 1 β Date Class with Overloaded Operators
The full Date class example demonstrates both overloaded operators in action.
#include <iostream.h>
class Date {
public:
Date() {
cout << "\n Parameterless constructor called ...";
month = day = year = 0;
}
~Date() { }
friend ostream & operator << (ostream & os, Date d);
friend istream & operator >> (istream & is, Date & d);
private:
int month, day, year;
};
ostream & operator << (ostream & os, Date d) {
os << d.day << "." << d.month << "." << d.year;
return os;
}
istream & operator >> (istream & is, Date& d) {
cout << "\n\n Enter day of the date: ";
cin >> d.day;
cout << " Enter month of the date: ";
cin >> d.month;
cout << " Enter year of the date: ";
cin >> d.year;
return is;
}
main(void) {
Date date1, date2;
cout << "\n\n Enter two dates";
cin >> date1 >> date2;
cout << "\n Entered date1 is: " << date1 << "\n Entered date2 is: " << date2;
}
The output shows cascading input (cin >> date1 >> date2) and cascading output (cout << date1 << date2), supported by the return of references to istream and ostream.
Example 2 β Matrix Class with Overloaded Operators
This example shows a Matrix class first without overloaded operators, requiring specific functions getMatrix() and displayMatrix(). Then, it is modified to use overloaded << and >>, which improves readability and convenience.
Original version (without overloaded operators):
class Matrix {
// ...
public:
Matrix(int rows = 0, int cols = 0);
void getMatrix();
void displayMatrix();
};
// Usage:
Matrix matrix(2, 2);
matrix.getMatrix();
matrix.displayMatrix();
Modified version (with overloaded operators):
class Matrix {
float elements[30][30];
int numRows, numCols;
public:
Matrix(int rows = 0, int cols = 0) {
numRows = rows;
numCols = cols;
}
friend ostream & operator << (ostream &, Matrix &);
friend istream & operator >> (istream &, Matrix &);
};
istream & operator >> (istream & input, Matrix & m) {
for (int i = 0; i < m.numRows; i++) {
for (int j = 0; j < m.numCols; j++) {
input >> m.elements[i][j];
}
}
return input;
}
ostream & operator << (ostream & output, Matrix & m) {
for (int r = 0; r < m.numRows; r++) {
for (int c = 0; c < m.numCols; c++) {
output << m.elements[r][c] << '\t';
}
output << endl;
}
return output;
}
int main() {
Matrix matrix(3, 3);
cout << "\nEnter a 3 * 3 matrix \n\n";
cin >> matrix;
cout << "\nEntered matrix is: \n";
cout << matrix;
// ...
}
The output shows the matrix is entered and displayed using the familiar cin >> matrix and cout << matrix syntax, rather than calling specialized member functions. This makes the code more intuitive and readable.
π‘ Why this matters: Overloading << and >> allows user-defined classes to behave like built-in types, making the interface consistent and reducing the learning curve for other programmers.
Tips
The lecture concludes with essential tips for implementing these operators:
- Stream insertion (
<<) and extraction (>>) operators are always implemented as non-member functions. operator <<returnsostream &andoperator >>returnsistream &to support cascaded operations.- The first parameter to
operator <<is anostream &object (e.g.,cout). Similarly, the first parameter tooperator >>is anistream &object (e.g.,cin). These first parameters are always passed by reference; the compiler won't allow otherwise. - For
operator >>, the second parameter must also be passed by reference. - The second parameter to
operator <<is an object of the class for which we are overloading the operator. The same applies tooperator >>.
β Key Takeaways
Stream insertion (<<) and extraction (>>) operators must be overloaded as non-member functions (typically declared as friends of the class) because the left operand is always a stream object (cin/cout), not an object of the user-defined class. Both operators must return a reference to the appropriate stream type (ostream& for <<, istream& for >>) to support cascading. The first parameter for both operators must be passed by reference to the stream object. For the extraction operator (>>), the second parameter (the object being read into) must also be passed by reference because it is modified; for the insertion operator (<<), passing the second parameter by reference is optional but improves performance. Using these overloaded operators makes user-defined classes behave like native types, improving code readability and programmer convenience.
π§ Quick Revision Questions
- Why can't stream insertion (
<<) and extraction (>>) operators be overloaded as member functions of a class? - What return type must an overloaded
<<operator have, and why? - In the prototype
istream & operator >> (istream & input, Date & d), why mustdbe passed by reference? - What is the purpose of declaring the overloaded operator function as a
friendof the class? - In the
Matrixexample, why is passing the second parameter (Matrix & m) by reference in the<<operator considered "optional but efficient"?
π Lecture 38 β Lecture No. 38
π Overview: This lecture covers two important programming concepts: user-defined manipulators and the static keyword. User-defined manipulators allow programmers to create custom formatting tools for output streams, while the static keyword provides a mechanism for maintaining state across function calls and within classes. These concepts are essential for writing more flexible and efficient C++ programs.
ποΈ Topics Covered
The lecture begins with user-defined manipulators, explaining how to create custom manipulators like bell, tab, and matrix formatting tools. It then explores the static keyword thoroughly, covering static variables within functions, static objects, and static data members of a class. The lecture provides detailed examples for each concept, including a complete matrix display program and programs demonstrating the lifetime and behavior of static versus automatic variables.
π Lecture Summary
User Defined Manipulators
We have talked a lot about the manipulators that are provided with the streams in the C++. These are similar to setw function, used to set the width of the output. To write our own manipulator, we need to understand parameter-less manipulators like endl, which inserts a new line and flushes the buffer. In case of operator overloading, it is pre-requisite to know where the operator will be used. With manipulators, a stream object (normally cout, an ostream object) appears on the left-hand side. The cout takes the manipulator to carry out some manipulation. These are written in cascading style as cout << manipulator << "some data" << endl.
The left-hand side will be an ostream object that will call the manipulator. Normally, on the right-hand side of the manipulator, we have another stream insertion operator <<. For a parameter-less manipulator, no argument is passed. The manipulator should return a reference to an ostream object, so cascading works. Since the ostream class is built-in and cannot be modified, the manipulator is not a member function β it is a standalone function. The declaration of this manipulator is:
ostream& manipulator_name (ostream& os)
The argument os is the same object which is calling this function. Inside the definition, the manipulator should only do something regarding output and return the ostream reference.
π Definition β Parameter-less manipulator: A manipulator that takes no arguments and operates on an output stream, returning a reference to the stream object to allow cascading.
π Formula: ostream& manipulator_name (ostream& os) { return os << 'character'; } β The function receives the output stream, performs an output operation, and returns the stream reference.
π Example: To create a bell manipulator:
ostream & bell ( ostream & output ) {
return output << '\a';
}
Usage: cout << "Virtual " << tab << "University" << bell << endLine;
Examples of user defined manipulator
The lecture presents a complete program demonstrating user-defined manipulators for formatting a matrix display. Various manipulators are defined to control spacing, lines, stars, and sounds. The manipulators include spaceFirst (sets width to 33), spaceBetween (sets width to 4), line (inserts "|"), newLine (inserts endl), star (inserts "*"), and sound (inserts beep). These manipulators are used as friend functions of the Matrix class to format the output of a 3x3 matrix with borders and proper spacing.
The output of the matrix program displays:
******************************Displaying The Matrix*****************************
| 3 5 1 |
| 8 7 6 |
| 2 5 2 |
π‘ Why this matters: User-defined manipulators allow programmers to create reusable, readable formatting tools that work naturally with C++ stream syntax, making output code cleaner and more maintainable.
Static keyword
The word static refers to something that is stationary, stopped, and not moveable. Static variables exist for a certain amount of time, much longer than ordinary automatic variables. There are different types of variables based on lifetime. Global variables are defined outside of main, exist for the entire program execution, and are accessible from everywhere β but this can cause problems as they are visible in functions that don't need them. Automatic variables (local variables inside functions) are created when a function is called and destroyed when it returns.
Static variables provide a middle ground: they maintain state across function calls but are not visible outside the function. Using the static keyword inside a function creates a variable that is initialized only once during the program's lifetime and retains its value between function calls. The declaration is: static int i;. Unlike ordinary variables, static variables must be initialized at the point of declaration (e.g., static int i = 0;), not through a separate assignment. Static variables are stored in a static memory area, separate from the stack (for automatic variables) and the heap/free store (for dynamic memory).
π Definition β Static variable: A variable declared with the static keyword inside a function that is created and initialized only once during the lifetime of the program, maintaining its value between function calls.
π Formula: static data_type variable_name = initial_value; β Creates a static variable that persists for the program's lifetime.
π Example: Compare static and automatic variables:
void staticVarFun() {
static int i = 0; // initialized only once
i++;
cout << "The value of i is:" << i << endl;
}
void nonstaticVarFun() {
int i = 0; // initialized every call
i++;
cout << "The value of i is:" << i << endl;
}
When called 10 times, staticVarFun() outputs 1,2,3...10 while nonstaticVarFun() outputs 1,1,1...1.
Static Objects
User-defined data types (classes and objects) can also be declared as static. When we create a static object inside a function, it must be initialized. Since initialization is done in constructors, it is necessary to provide a constructor with default arguments so the object can be properly initialized when created as static. The behavior of a static object is the same as a static variable of a native data type β it maintains its state and exists even outside the function.
The lecture demonstrates the lifetime of static objects using a truck class with constructors and destructors that print messages. The program creates: a global object A('A'), an ordinary object B('B') in main, an automatic object C('C') in function f(), and a static object D('D') in function g(). The output shows:
inside the constructor of A
inside the constructor of B
inside the constructor of C
Inside the destructor of C
inside the constructor of D
Inside the destructor of B
Inside the destructor of D
Inside the destructor of A
Notice that the static object D is NOT destroyed when function g() finishes β it persists until program termination. The destruction order is: local variables of main first (B), then static objects (D), then global objects (A). This shows that static objects remain for a longer period of time.
π Definition β Static object: An object declared with the static keyword inside a function that is created and initialized only once and maintains its state across function calls.
π Example: static truck D('D'); β This object persists beyond the function scope and is destroyed only when the program ends.
Static data member of a class
The static data member concept extends static variables to the class level. A static data member is a single copy that belongs to the class itself, not to any individual object. It is created once and initialized once for the entire class, stored in the static memory area. Its lifetime is the lifetime of the program. Static data members are initialized at file scope (outside of main and any functions) using the scope resolution operator: ClassName::static_member = value;
Static data members can be public or private and can be accessed by objects of the class, but it is recommended to access them with the class name, not an object name, to avoid confusion. Changing a static data member through one object changes it for all objects of that class.
π Definition β Static data member: A data member of a class declared with the static keyword that has only one copy shared by all objects of the class, initialized at file scope.
π Formula: class ClassName { static int member; }; int ClassName::member = value; β Creates a class-level variable shared by all instances.
π Example: For a savingsAccount class:
class savingsAccount {
static double profit_rate; // same for all accounts
// other members...
};
double savingsAccount::profit_rate = 3.0; // initialization at file scope
This profit rate applies to all PLS accounts. If one object changes it via account1.profit_rate = 4.0;, it changes for ALL accounts β which is why accessing it with class name (savingsAccount::profit_rate) is preferred.
Another useful example: counting the number of student objects:
class student {
static int how_many;
public:
student() { how_many++; }
~student() { how_many--; }
};
int student::how_many = 0; // initialize to zero
This automatically tracks the number of student objects as they are created and destroyed.
π‘ Why this matters: Static data members provide an elegant way to share state across all objects of a class without using global variables, and can be used for tracking object counts, shared configuration settings, or class-wide constants.
β Key Takeaways
- User-defined manipulators must return a reference to an ostream object and take an ostream reference as a parameter, allowing them to be used in cascading stream expressions like built-in manipulators.
- Static variables inside functions maintain their value between function calls, being initialized only once during the program's lifetime, and are destroyed only when the program ends β unlike automatic variables that are created and destroyed with each function call.
- Static objects follow the same lifetime rules as static variables but require constructors with default arguments for proper initialization; they are not destroyed when the function returns but persist until program termination.
- Static data members are class-level variables shared by all objects, initialized at file scope using the scope resolution operator, and changing them through any object affects all objects of that class.
- Static provides an alternative to global variables by maintaining state while limiting visibility and side effects, making programs more modular and less prone to errors from unintended access.
π§ Quick Revision Questions
- What is the correct signature and return type for a user-defined parameter-less manipulator?
- Why does a static variable inside a function retain its value between function calls, and what happens if you omit the
statickeyword? - In the truck class example, why was the static object
Dnot destroyed when functiong()finished, and when was it finally destroyed? - How do you initialize a static data member of a class, and why must this be done at file scope rather than in a constructor?
- What is the danger of accessing a static data member through an object name (e.g.,
account1.profit_rate) instead of the class name (e.g.,savingsAccount::profit_rate)?
π Lecture 40 β Objects as Class Members
π Overview: This lecture explores how classes can contain objects of other classes as data members, focusing on construction and destruction ordering. It demonstrates member initializer lists for efficient initialization and introduces nested classes, explaining how inner classes can be used within outer classes for better code organization and reusability.
ποΈ Topics Covered
The lecture covers objects as class members with construction and destruction sequences, member initializer lists for parameterized constructor calls, examples using Date, Column/Row/Matrix, and VehicleParts structures, advantages of code reuse, structures as class members, nested classes with public/private visibility, friend declarations between nested classes, and practical tips for implementing these concepts.
π Lecture Summary
Objects as Class Members
A class is a user-defined data type that can be used inside other classes just like native data types. We can create classes that contain objects of other classes as data members. When one class contains objects of other classes, it is mandatory to understand how and in what sequence the contained and containing objects are constructed. The contained data members of the object (regardless whether they are native or user-defined data types) are constructed before the object itself. The order of destruction of an object is reverse to this construction order, where the containing object is destroyed first before the contained objects.
π Definition β Initializer List: A colon placed after the parameter list of the containing class's constructor, followed by the name of the member and a list of arguments, used to initialize contained objects at construction time.
π Construction Order Rule: Inner data members are constructed first β Containing object is constructed last. Destruction is the reverse: Outermost object destroyed first β Inner members destroyed last.
π Example: Class A contained in Class B:
class A { /* constructor/destructor */ };
class B {
public:
B() { cout << "B Constructor"; }
~B() { cout << "B Destructor"; }
private:
A a; // contained object
};
// Output: A Constructor β B Constructor β B Destructor β A Destructor
Example 1
A PersonInfo class stores name, address, and birthday of a person, containing an instance of a Date class to store birthday. No arguments are specified in the declaration of birthday, but a member initializer can be used to call a parameterized constructor. The colon is placed after the parameter list of the containing class's constructor, followed by the member name and arguments. Multiple contained objects can be initialized using comma-separated initializers. The order of execution of initializers is the same as the order of declarations of objects inside the outer class, not the order in the initializer list.
π‘ Why this matters: This ensures that objects are initialized in a predictable order, preventing dependency issues.
π Definition β Member Initializer Syntax: ClassName::ClassName(params) : memberName(params_for_member) { body }
π Example: PersonInfo with birthday and drvLicenseDate:
PersonInfo::PersonInfo(char* nm, char* addr, int month, int day, int year,
int licMonth, int licDay, int licYear)
: drvLicenseDate(licMonth, licDay, licYear), birthday(month, day, year)
{
cout << "\n PersonInfo -- Constructor called ...";
}
// Output: birthday constructor first (declared first), then drvLicenseDate constructor,
// then PersonInfo constructor. Destruction reverses.
Example 2
This example works with the size of a matrix. A Column class stores column size, a Row class contains a Column instance to store number of columns, and a Matrix class contains a Row instance. The construction sequence is: Column object constructed first, then Row object, finally Matrix object. At destruction, the order reverses: Matrix destroyed first, then Row, then Column.
π Definition β Nested Object Construction: The innermost contained object is constructed first, then each containing level, with the outermost object constructed last.
π Example: Matrix(3, 4) β Output sequence: Column created β Row created β Matrix created β Matrix destroyed β Row destroyed β Column destroyed
π Public member access: Public data members of a contained object can be accessed from outside using the dot operator:
Matrix matrix(4, 5);
Matrix.row.size = 8; // only if row is public and has public size member
Advantages of Objects as Class Members
This is a way of reusing code when we contain objects of already written classes into a new class. The Date class can be used as a data member of Student, Employee, or PersonInfo class. Previously written classes don't need to be tested again β they are added to a components library for later use. This approach gives clarity and better management to source code by breaking problems into smaller components that can be managed independently. When an object is declared as a constant data member inside a class, it is initialized using the initializer list, requiring the contained class to have a parameterized constructor.
Structures as Class Members
Structures and classes are very similar in C++ except the default scope of members. The default scope for members of structures is public, whereas the default visibility for class members is private. All the discussion for class objects as class members applies to structure objects as class members.
π Example: Vehicle class with VehicleParts structure:
struct VehicleParts {
int wheels;
int seats;
VehicleParts(int w, int s) : wheels(w), seats(s) { }
};
class Vehicle {
private:
VehicleParts vehicleParts;
public:
Vehicle(int a, int b) : vehicleParts(a, b) { }
};
// Output: VehicleParts - parameterized constructor β Vehicle - parameterized constructor
Classes inside Classes
Classes defined within other classes are called nested classes. A nested class is written exactly like a normal class with data members, member functions, constructors, and destructors, but no memory is allocated unless an instance is created. C++ allows multiple levels of nesting. If a class is nested inside the public section of a class, it is visible outside the outer class. If nested in the private section, it is only visible to the members of the outer class.
π Definition β Nested Class: A class defined within another class, used to keep associated classes together for easier manipulation of objects.
π Visibility rules: The outer class has no special privileges regarding the inner class β the inner class has full control over the accessibility of its members. The friend operator can be used to declare the enclosed class as a friend of the inner class to provide access to private members.
π Member function definition: Nested class member functions can be defined outside the surrounding class using scope resolution:
Surround::FirstWithin::FirstWithin() { variable = 0; }
π Friend declarations example: To allow all three classes (Surround, FirstWithin, SecondWithin) to access private members of each other:
class Surround {
friend class FirstWithin;
friend class SecondWithin;
// ...
class FirstWithin {
friend class Surround;
friend class SecondWithin;
// private members
};
class SecondWithin {
friend class Surround;
friend class FirstWithin;
// private members
};
};
Structures can also be defined inside classes in the same manner, with the exception that default scope of members in structures is public unless explicitly declared otherwise.
β Key Takeaways
A class can contain instances of other classes as its data members, which is a powerful technique for code reuse. The construction order is always inner objects first, then the containing object, while destruction reverses this order. Member initializer lists provide an efficient way to initialize contained objects with parameterized constructors, and the order of initialization follows the declaration order in the class, not the order in the initializer list. Nested classes allow organizing related classes together, with visibility controlled by whether the inner class is declared in the public or private section of the outer class.
π§ Quick Revision Questions
- What is the construction and destruction order when Class B contains an instance of Class A as a data member?
- How does a member initializer list ensure contained objects are properly initialized with non-default constructors?
- In Example 1 with PersonInfo, why did the birthday constructor execute before drvLicenseDate's constructor even though drvLicenseDate appeared first in the initializer list?
- What are the visibility rules for a nested class declared in the public section versus the private section of the outer class?
- How can the friend operator be used to allow nested classes to access private members of each other?
π Lecture 41 β Template Functions
π Overview: This lecture introduces the concept of templates in C++ as a powerful code reuse mechanism. It covers function templates, their overloading, explicit type specification, and the integration of template functions with user-defined classes through operator overloading. This approach allows writing generic code once and letting the compiler generate type-specific versions automatically.
ποΈ Topics Covered
The lecture covers template functions as a new code reuse method, including their definition using the template keyword and generic data types. It explores overloading template functions with different argument signatures and explicitly specifying types in angle brackets. The discussion extends to using template functions with class objects, emphasizing the need for operator support within the class, and concludes with a recap combining templates with operator overloading.
π Lecture Summary
Template Functions
Templates in C++ provide a way to write generic code that works with any data type. Unlike function overloading where multiple versions of a function are written manually, a function template allows writing the code once, and the compiler automatically generates type-specific versions at compile time. The template is defined using the template<class T> syntax, where T is a generic data type placeholder. At least one function argument must be of the generic type. When the function is called, the compiler detects the argument type, substitutes T with that type, and generates the appropriate function code. For example, a swap function template can work for int, double, char, etc., without rewriting the function for each type.
π Definition β Template Function: A function defined with a generic data type that allows the compiler to generate type-specific versions automatically based on how it is called.
π Formula: template<class T> return_type function_name(T arg1, ...) { body } β The compiler replaces T with the actual type when generating the function.
π Example: The swap function template takes two references of generic type T and swaps their values using a temporary variable T tmp. Calling swap(a, b) with int a, b generates an int version; with char a, b, a char version is generated.
Overloading Template Functions
Overloaded template functions follow the same rules as ordinary function overloading β functions with the same name but different number or type of arguments. The compiler selects the correct version based on the arguments provided. This allows defining multiple template functions with the same name that perform different operations, as long as their signatures differ. For instance, one inverse template function might swap two values (void inverse(T &x, T &y)), while another returns the negative of a single value (T inverse(T x)). The compiler distinguishes between them by the argument count.
π Example: The program defines inverse(i) for a single argument returning its negative, and inverse(i, j) for swapping two values. The compiler generates appropriate versions for each call.
Explicitly Specifying the Type in a Template Function
When calling a template function, the type can be explicitly specified using angle brackets between the function name and the argument list, like function_name<type>(arguments). This is useful when we want to force the compiler to generate a version with a different return type or argument type than what would be inferred automatically. For functions with multiple generic types, types are specified left to right, similar to default arguments β the second type cannot be forced without specifying the first. This technique allows, for example, passing a double argument but generating an int version of the function that returns an int.
π Definition β Explicit Type Specification: Forcing the compiler to generate a specific version of a template function by writing the desired type(s) in angle brackets before the argument list.
π Formula: function_name<type1, type2>(arguments) β Forces T to become type1 and U to become type2 for template<class T, class U>.
π Example: With template<class T, class U> T reverse(U x), calling reverse<int, double>(amount) forces T = int and U = double, generating int reverse(double x).
Template Functions and Objects
Template functions can also work with user-defined class objects, provided the class supports all operations used inside the template function. When the compiler generates a template function for a class type, it replaces the generic type with the class type. If the template function uses operators like - (unary minus), the class must have that operator overloaded. For example, a reverse template function using -x can work with a PhoneCall class only if that class defines the unary minus operator to reverse the phone call (e.g., changing billCode to 'c' for cancelled). This demonstrates combining templates with operator overloading for powerful, reusable code.
π‘ Why this matters: The template function is written once independently, and the class independently defines its operator. The main program connects them, allowing the same generic code to work seamlessly with different classes.
π Definition β Template with Objects: Using a template function with a class object requires that all operations within the template (like -, +, comparison) are defined in the class through operator overloading.
π Example: The PhoneCall class defines unary minus operator to set billCode = 'c'. The reverse template function calls -x, which invokes this overloaded operator. Calling reverse(aCall) generates a PhoneCall version, changes the bill code to cancelled, and returns the modified object.
β Key Takeaways
The lecture establishes templates as a fundamental code reuse mechanism in C++. A function template uses template<class T> to define a function that works with any data type, and the compiler automatically generates type-specific versions. Template functions can be overloaded like regular functions, and types can be explicitly specified using angle brackets. When using templates with class objects, all operations in the template must be supported by the class through operator overloading. This combination of templates and operator overloading is extremely powerful for writing once that works across many types.
π§ Quick Revision Questions
- What is the syntax for defining a template function with one generic type, and what is the minimum requirement regarding arguments?
- How does the compiler handle a call to a template function with an
intargument versus adoubleargument? - Can a template function be overloaded? Under what conditions can two template functions have the same name?
- Write the explicit type specification syntax to force a template function with signature
template<class T, class U> T func(U x)to return anintwhen passed adoubleargument. - If a template function uses the
-operator, what must a class define before a template function can be used with objects of that class?