π Lecture 29 β Friend Functions and Friend Classes
π Overview: This lecture introduces the concept of friend functions and friend classes in C++ programming. It explains how external functions (non-member functions) and entire classes can be granted special access to the private data members of a class, why this is sometimes necessary, and the important limitations and precautions associated with using friendship in object-oriented programming.
ποΈ Topics Covered
The lecture covers the definition and purpose of friend functions, the syntax for declaring friend functions inside a class, and three sample programs demonstrating friend functions accessing private data of one and two classes. It then extends the concept to friend classes, where an entire class is granted access to another classβs private members, and discusses the critical principles of friendship: it is granted (not taken), one-way, and non-transitive. The lecture concludes with a summary emphasizing the careful use of friendship due to its violation of data encapsulation.
π Lecture Summary
6) Friend functions
The lecture begins by reviewing the concepts of class (a user-defined data type), encapsulation, and data hiding. Data members are typically declared private to be visible only from inside the class, while public member functions serve as the interface for the outside world. Normally, private data cannot be accessed directly from outside the class.
Sometimes, however, a need arises to access the private data of a class from outside. This is where the concept of friend functions becomes useful. A friend function of a class has access to the private data members of that class, even though it is not a member function of the class. The analogy used is that just as a friend has access to your inner thoughts and feelings, a friend function has access to the inner (private) data of a class. This is a powerful feature but introduces potential vulnerability, as it partially violates data encapsulation and data hiding.
π Definition β Friend Function: A non-member function that is declared as a friend of a class and, as a result, has access to all private data members and utility functions of that class.
π‘ Why this matters: Friend functions allow non-member functions to interact with a classβs private data when needed (e.g., operator overloading, interacting with multiple classes) without making the data public, but they weaken encapsulation and should be used sparingly.
7) Declaration of Friend Functions
To declare a friend function, place its prototype inside the class definition (in either the private or public section) preceded by the keyword friend. Friendship is a strong declaration and is not affected by public or private keywords. The definition of the friend function always appears outside the class (without the friend keyword). Usually, an object of the class is passed as a parameter to the friend function so it can access the objectβs private data.
Friend function prototype syntax inside a class:
friend return_type friend_function_name(int, char);
A class declares which functions are its friends β a function cannot declare itself a friend of a class from the outside. Friendship is granted, never taken. The class maintains control over what external functions can access its private members.
π Definition β Friendship is Granted, Never Taken: A class must explicitly declare a function or another class as its friend; an external function or class cannot declare itself a friend of a class.
π Example (Declaration):
class myClass {
friend void increment(myClass *, int); // Friend function declaration
private:
int topSecret;
public:
void display();
myClass();
};
8) Sample Program 1
This program demonstrates a friend function increment that accesses and modifies the private data member of a single class, myClass.
The class myClass has a single private data member int topSecret initialized to 100 by the constructor. The friend function increment is declared inside the class. Its definition is outside the class:
void increment(myClass *a, int i) {
a->topSecret += i; // Modify private data
}
In main(), an object x of type myClass is created. After displaying the initial value of topSecret (100), the friend function increment(&x, 10) is called. This directly modifies the private data topSecret of the object x, adding 10 to it. The subsequent display() call will show the new value (110). A non-friend function trying to access topSecret would result in a compiler error.
π Key Concept: Friend functions can directly modify private data members through an object pointer or reference.
π Formula (Friend Function Call): friend_function(&object, value); β object.privateData += value;
π Example (Program 1 Code):
#include <iostream.h>
class myClass {
friend void increment(myClass *, int);
private:
int topSecret;
public:
void display() { cout << "\n The value of the topSecret is " << topSecret; }
myClass();
};
myClass::myClass() { topSecret = 100; }
void increment(myClass *a, int i) {
a->topSecret += i;
}
main() {
myClass x;
x.display(); // Output: 100
increment(&x, 10);
x.display(); // Output: 110
}
Output:
The value of the topSecret is 100
The value of the topSecret is 110
9) Sample Program 2
This program demonstrates a friend function addBoth that has access to private data members of two different classes, myClass1 and myClass2. This is a common use case for friend functions.
myClass1 and myClass2 each have a private data member int topSecret (initialized to 100 and 200 respectively). A standalone function addBoth is needed to add the topSecret values from objects of both classes. To give it access to both classes' private data, addBoth is declared as a friend function inside both class definitions.
Because myClass2 is referenced in the friend declaration inside myClass1 before myClass2 is defined, a forward declaration of myClass2 is required before the definition of myClass1:
class myClass2; // Forward declaration
π Definition β Forward Declaration: A declaration that tells the compiler that a class name exists (e.g., class myClass2;), allowing it to be referenced before its full definition.
π Example (Friend function of two classes):
class myClass2; // Forward declaration
class myClass1 {
private:
int topSecret;
public:
void display() { cout << "\nThe value of the topSecret is " << topSecret; }
myClass1() { topSecret = 100; }
friend void addBoth(myClass1, myClass2);
};
class myClass2 {
private:
int topSecret;
public:
void display() { cout << "\nThe value of the topSecret is " << topSecret; }
myClass2() { topSecret = 200; }
friend void addBoth(myClass1, myClass2);
};
void addBoth(myClass1 a, myClass2 b) {
cout << "\nThe sum of values of topSecret in myClass1 and myClass2 is " << a.topSecret + b.topSecret;
}
Output:
The value of the topSecret is 100
The value of the topSecret is 200
The sum of values of topSecret in myClass1 and myClass2 is 300
10) Sample Program 3
This program expands on Program 2 by creating multiple friend functions (addBoth, subBoth, mulBoth, divBoth) for the same two classes. The program prompts the user to enter an operator (+, -, *, /) and then calls the corresponding friend function to perform the requested arithmetic operation on the private value data members of objects of myClass1 and myClass2.
All friend functions are declared in both classes. Their definitions are placed at the end of the file, returning a float result. This example shows that a class can have multiple friend functions for different purposes.
π Example (User interaction with friend functions):
// Inside main()
myClass1 myClass1Obj; // value = 200
myClass2 myClass2Obj; // value = 100
// If user enters '*'
cout << "The multiplication is : " << mulBoth(myClass1Obj, myClass2Obj) << endl;
Output (when '*' is entered):
The multiplication is : 20000
11) Friend Classes
The concept of friendship extends from individual functions to entire classes. A class can be declared as a friend class of another class. When a class is declared as a friend, all member functions of the friend class gain access to the private data members and functions of the class that granted the friendship.
Syntax for declaring a friend class (inside the granting class):
friend class ClassName;
// or
friend ClassName;
The key principles of friend classes mirror those of friend functions:
- Friendship is granted, not taken: The class declares which other classes are its friends.
- Friendship is one-way: If
OtherClassis a friend ofClassOne,OtherClasscan accessClassOne's private members, butClassOnecannot accessOtherClass's private members unlessOtherClassalso declaresClassOneas a friend. - Friendship is not transitive: If
Ais a friend ofB, andBis a friend ofC, it does not meanAis a friend ofC.Amust be explicitly declared as a friend byC.
π Definition β Friend Class: A class whose all member functions have access to the private data members and methods of another class that has declared it as a friend.
π Example (Friend class):
class ClassOne {
friend class OtherClass; // OtherClass is a friend of ClassOne
private:
int topSecret;
};
class OtherClass {
public:
void change(ClassOne co) {
co.topSecret++; // Can access private data of ClassOne
}
};
π‘ Why this matters: Friend classes can be useful when two classes are tightly related (e.g., a StraightLine class and a Quadratic class that need to interact for mathematical intersection calculations). However, they introduce strong coupling and should be used very sparingly as they violate encapsulation. Changes to the implementation of one class may require changes in the friend class.
12) Summary
The lecture concludes with a summary of key points. Classes allow separation of implementation from interface. Private data members are hidden from outside access. Friend functions are non-member functions that are granted access to a class's private data. Friend classes extend this concept so that all member functions of one class can access the private data of another. Friendship is a useful feature but must be used carefully and sparingly as it negates the core object-oriented principles of encapsulation and data hiding. The fundamental principles of friendship are:
- Friendship is granted, not taken.
- Friendship is not reciprocal (one-way unless explicitly declared both ways).
- Friendship is not transitive.
β Key Takeaways
The most critical concepts from this lecture are: (1) Friend functions are non-member functions that, when declared with the friend keyword inside a class definition, gain full access to that class's private data members and utility functions; (2) Friendship is strictly controlled by the class (the class grants friendship, an external function/class cannot take it); (3) A friend function can be a powerful tool when a function needs to access the private data of two or more different classes (like adding private values from two separate class objects); (4) The concept extends to friend classes where all member functions of one class gain access to another class's private members; (5) Friendship is one-way and non-transitive, and it must be used very sparingly as it directly violates the principles of data hiding and encapsulation by exposing a class's internal structure.
π§ Quick Revision Questions
- What is the purpose of declaring a friend function, and what access does it have to a class?
- Can a function declare itself a friend of a class from outside the class definition? Explain why or why not.
- In Sample Program 2, why is a forward declaration
class myClass2;needed before definingmyClass1? - Explain the difference between a friend function and a friend class. What are the implications of using a friend class on code maintainability?
- If Class A declares Class B as its friend, and Class B declares Class C as its friend, does Class A automatically have access to Class C's private members? Explain the principle at play here.
π Lecture 30 β Reference Data Type
π Overview: This lecture introduces the reference data type in C++, explaining how references serve as aliases or synonyms for existing variables. It covers the declaration, initialization, and practical applications of references, particularly in implementing efficient call-by-reference in functions, and compares references with pointers while discussing dangers like dangling references.
ποΈ Topics Covered
The lecture covers reference data type declaration and initialization, examples showing how references work as synonyms, comparing call by value vs call by reference using pointers and references, using const with references for safety, implementing swap function with references, differences between references and pointers, references as return values, dangling references, and how cout statements work by returning references.
π Lecture Summary
Reference data type
Today's topic is about references, which is very important from the C++ perspective. C++ defines a way to create an alias or synonym of any data type, called a reference. We declare it using the & operator, but this is confusing because we also use & as the address-of operator. We write int &i; which means that i is a reference to an integer β easier to read from right to left. A reference has to be initialized when declared. For example: int &j = i; declares j as another name for i β it does NOT create a new variable, just a new name for the existing variable. Manipulating either i or j manipulates the same memory location.
π Definition β Reference: A synonym or alias that provides another name for an existing variable. It must be initialized when declared and cannot be reassigned to refer to a different variable.
π Declaration Syntax: datatype &reference_name = existing_variable; β Creates an alias for the existing variable
π Example:
int i;
int &j = i; // j is a reference to i
i = 123;
cout << i; // displays 123
cout << j; // also displays 123
i++;
cout << i; // displays 124
cout << j; // also displays 124
Both i and j refer to the same memory location.
π‘ Why this matters: References provide an elegant way to implement call-by-reference without the cumbersome pointer notation (using * for dereferencing).
Example 1
The lecture presents an example using a structure bigone with a string of 1000 characters, demonstrating three ways to pass it to functions:
- Call by value (
valfunc(bigone v1)) β copies the entire structure onto the stack - Call by pointer (
ptrfunc(const bigone *p1)) β passes address using&bo - Call by reference (
reffunc(const bigone &r1)) β passes reference, looks like call by value
The const keyword with references prevents the function from modifying the original data while maintaining efficiency. The function gets the address but cannot change the original value β providing efficiency of call by reference and safety of call by value.
π Example Code Snippet:
struct bigone {
int serno;
char text[1000];
} bo = {123, "This is a BIG structure"};
void valfunc(bigone v1); // Call by value
void ptrfunc(const bigone *p1); // Call by pointer
void reffunc(const bigone &r1); // Call by reference
int main() {
valfunc(bo); // copies entire structure
ptrfunc(&bo); // passes address
reffunc(bo); // passes reference (looks like value call)
}
Difference Between References and Pointers
- References must be initialized when declared; pointers can be declared without initialization
- References cannot be NULL; pointers can be NULL
- Once initialized, a reference cannot be reassigned to refer to another variable
- No arithmetic can be performed on references (no increment, decrement, or reassignment), unlike pointers
- References are primarily used for implementing call by reference with a clean interface
π Definition β Dangling Reference: A reference that points to a memory location that no longer exists (e.g., returning a reference to a local variable that goes out of scope).
Example 2
Functions can return references. The syntax is: datatype& function_name(parameter list). For example: int& num();
When a function returns a reference to a global variable (which exists throughout the program), it can even appear on the left side of an assignment statement, like num() = 200; which is equivalent to assigning to the global variable. However, this is confusing and considered bad practice.
π Example:
int myNum = 0; // Global variable
int& num() {
return myNum; // Returns reference to global variable
}
int main() {
int i;
i = num(); // i gets value of myNum (0)
num() = 200; // Equivalent to myNum = 200
cout << myNum; // Displays 200
}
β οΈ Danger: Never return a reference to a local variable β that variable dies when the function returns, creating a dangling reference. Use global or static variables instead.
β Key Takeaways
References are aliases that must be initialized when declared and cannot be reassigned. They provide an elegant way to implement call-by-reference without pointer notation β use const with references to combine efficiency with safety. References cannot be NULL and do not support arithmetic operations. Never return a reference to a local variable to avoid dangling references. Functions returning references should use global or static variables. The & operator acts as a reference declarator in declarations but as address-of operator in code.
π§ Quick Revision Questions
- What is a reference in C++ and how is it different from a pointer?
- Why must a reference be initialized when declared?
- How does using
constwith references provide both efficiency and safety? - What is a dangling reference and how can it be avoided?
- Can a reference be reassigned to refer to a different variable after initialization?
π Lecture 32 β Lecture No. 32
π Overview: This lecture continues the discussion on operator overloading in C++, focusing on overloading the minus operator, implementing operators with the Date class, and handling unary operators. It emphasizes the importance of meaningful operator definitions and the careful attention to detail required when designing robust classes.
ποΈ Topics Covered
The lecture covers overloading the minus and minus-equal operators for the Complex class, determining which operators are meaningful for different classes, implementing date arithmetic with a full Date class (including plus and pre-increment operators), and discussing unary operators with the examples of pre/post increment. It also addresses comparison operators, friend functions, and code reuse principles through utility functions.
π Lecture Summary
Recap
Before further discussing operator overloading, it is necessary to know that new operators (new symbols) cannot be introduced β only existing symbols can be overloaded. Overloading operators is exactly like writing functions; however, one should remain close to the original meaning of the operator. It is bad practice to define something in opposite terms (e.g., plus operator doing subtraction). Under operator overloading, binary and unary operators will remain unchanged β we cannot make a unary operator work as a binary operator or vice versa. In the case of binary operators, the driving force is the left-hand operand.
Overloading Minus Operator
The process of defining the minus operator (-) for the Complex class is similar to the plus operator. It is a binary operator having two arguments, both complex numbers. When subtracting two complex numbers, it returns a complex number: subtract the real part from real part and subtract the imaginary part from imaginary part.
π Definition β Member Operator: When defining as a member operator, only one argument is passed (the right-hand side operand). The left-hand side calls this and is already available to the function.
π Formula:
Complex operator β (Complex c) {
Complex tmp;
tmp.real = real β c.real;
tmp.imag = imag β c.imag;
return tmp;
}
π Example: For the minus equal operator (-=), the value of the calling party (left-hand side) will be changed. No temporary complex number is needed:
Complex Complex::operator -= (Complex c) {
real -= c.real;
imag -= c.imag;
}
π‘ Why this matters: Overloading minus for the string class does not make sense. Only define operators that are self-explanatory, readable, and understandable. The thing to understand is that every operator does not make sense for every class.
Operators with Date Class
For the Date class, adding a number to a date (e.g., today's date plus 5) makes sense β we get a new date. Subtracting a number also makes sense. However, subtracting two dates requires careful consideration.
Adding an integer to a date involves complex logic because of:
- Different month lengths (30 or 31 days)
- February with 28 or 29 days (leap year)
- End of year transitions
π Definition β Leap Year Rules: If the year is divisible by 4, it is a leap year. For century years, it must be divisible by 400.
π Formula: The Date class implementation includes:
const int Date::daysInMonth[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
bool Date::leapYear(int y) {
if ((y%400 == 0) || (y%100 != 0 && y%4 == 0))
return true;
else
return false;
}
π Example: The plus operator implemented using a loop that calls the pre-increment operator:
Date Date::operator + (int numberOfDays) {
for (int i = 1; i <= numberOfDays; i++) {
++(*this);
}
return *this;
}
π Example: The pre-increment operator adds one day:
Date Date::operator ++ () {
if (day == daysOfMonth(*this) && month == 12) {
day = 1;
month = 1;
++year;
}
else if(day == daysOfMonth(*this)) {
day = 1;
++month;
}
else {
day++;
}
}
π‘ Why this matters: Date arithmetic is very important in business applications. It simplifies calculating vacation end dates, payment periods, and other date-based calculations.
Unary Operators
Unary operators take one argument (like i++ or ++i). You cannot make a unary operator into a binary operator or vice versa.
π Definition β Pre-increment Operator (++): Adds one day to the current date. As a member function, it takes no argument and returns a Date object.
π Formula: Prototype for pre-increment: Date operator ++ ();
To distinguish pre-increment from post-increment, an int argument is passed to the post-increment version:
Date operator ++ (int); // post increment operator
The lecture shows how code reuse works: the plus operator uses the pre-increment operator, and the pre-increment operator uses the daysOfMonth utility function. Don't repeat code inside a class β make a function for repeated code and call it where needed.
π Example: Comparison operators can also be overloaded. The greater-than operator returns bool:
bool Date :: operator > (Date d) {
if (year > d.year) return true;
else if (year == d.year) {
if (month > d.month) return true;
else if (month == d.month) {
if(day > d.day) return true;
else return false;
}
else return false;
}
else return false;
}
π Example: For integer + date, a friend function is needed because the integer is on the left-hand side (not a Date object). The friend function gets both arguments and can access the internal structure of the Date class.
π‘ Why this matters: Friend operators can glue two classes together. A classic example is multiplying a vector with a matrix β the multiplication operator will be a friend of both classes.
β Key Takeaways
The most critical things to remember from this lecture are: (1) Only overload operators that make logical sense for the class, and maintain their original meaning to keep code readable. (2) When implementing date arithmetic, pay careful attention to all edge cases including leap years, month lengths, and year transitions. (3) Use code reuse by calling simpler operators from more complex ones (e.g., using ++ inside the + operator). (4) Create utility functions (like daysOfMonth) as private members to centralize logic and avoid code duplication. (5) Use friend functions when the left-hand operand is not an object of the class, such as when adding an integer to a date.
π§ Quick Revision Questions
- Why should you avoid defining the minus operator for the string class?
- What are the three main cases to handle in a pre-increment operator for the Date class?
- How do you distinguish between pre-increment and post-increment operator prototypes?
- When would you use a friend function instead of a member function for operator overloading?
- What is the logic for comparing two dates using the greater-than operator?
π Lecture 33 β Operator Overloading
π Overview: This lecture explores advanced operator overloading techniques in C++, focusing on the assignment operator and its proper implementation to handle dynamic memory. It introduces the
thispointer and its role in enabling chained assignments and preventing self-assignment errors. The lecture also covers type conversions between user-defined and built-in types, using constructors and conversion operators, with practical examples from String, Date, and Fraction classes.
ποΈ Topics Covered
The lecture covers the need for and implementation of assignment operators in classes with dynamic memory, using the String class as a primary example. It introduces the this pointer for self-assignment checking and returning values from functions. The discussion extends to conversion techniques between user-defined and built-in types, demonstrating both constructor-based and conversion operator approaches. Practical examples include the Date class and the Fraction class for exact arithmetic.
π Lecture Summary
Operator Overloading
Operator overloading enables writing clean, simple code when working with user-defined types. When we add two objects of a class using a + b, we are adding two instances of a user-defined data type. In object-oriented programming, more effort is made in class definitions so that classes know how to manipulate themselvesβhow to add objects of their own type, how to display themselves, and perform other operations. For example, incrementing a date should be encapsulated within the Date class itself, not in the main program.
Assignment Operator
The question arises whether we need an assignment operator. It is needed when we want to assign one object to another, like a = b. C++ provides a default assignment operator that performs member-wise copy. For a class with three integers and two floats, writing a = b copies each member individually. However, this default behavior can cause problems in special cases.
Consider a String class with a data member *buf (a pointer to character array). If we write s2 = s1, the default assignment operator copies the pointer value (address), not the string content. Both objects end up pointing to the same memory location. If we delete s1, its destructor frees that memory, leaving s2's pointer dangling, pointing to deallocated memory.
The solution is to write our own assignment operator. The code should:
- Delete the existing buffer of the left-hand side object
- Allocate new memory of the right size
- Copy the string content, not just the pointer
void String::operator = ( const String &other )
{
int length;
length = other.length();
delete buf;
buf = new char [length + 1];
strcpy( buf, other.buf );
}
π Definition β Default Assignment Operator: A member-wise copy operator automatically provided by C++ that copies data members individually from one object to another, which can cause problems with pointer members.
π Formula: strcpy( buf, other.buf ) β Copies the actual string content from the source object's buffer to the destination object's buffer.
π Example:
String myString( "here's my string" );
String yourString( "here's your string" );
yourString = myString; // Calls our custom assignment operator
// After assignment, yourString displays "here's my string" in its own memory location
π‘ Why this matters: Whenever objects allocate memory (using new), we must define an assignment operator. Otherwise, the default operator only copies pointer addresses, leading to double deletion and memory corruption.
this Pointer
Whenever an object calls a member function, the function implicitly receives a pointer from the calling object, known as the this pointer. this is a keyword and cannot be used as a variable name. It refers to the calling object.
Three equivalent ways to refer to a member buf of the String class:
bufβ directly refers to the calling object's memberthis->bufβ uses the pointer notation(*this).bufβ dereferences the pointer (parentheses are necessary because dot operator binds stronger than*)
Self Assignment
Self-assignment occurs when an object is assigned to itself, like s = s. While this seems harmless for integers, it's dangerous for classes with dynamic memory. Our assignment operator first deletes the calling object's buffer, then tries to copy from the right-hand side object. In self-assignment, the buffer of s is deleted, and then the code tries to use it for copyingβcausing unpredictable behavior.
Self-assignment can occur indirectly, for example:
String s, *sptr;
sptr = &s;
s = *sptr; // This is effectively s = s;
To prevent this, we check if the calling object is the same as the passed object:
void String::operator=( const String &other )
{
if( this == &other )
return; // Self-assignment detected, do nothing
delete buf;
length = other.length;
buf = new char[length + 1];
strcpy( buf, other.buf );
}
Returning this Pointer from a Function
For chained assignments like s3 = s2 = s1, the assignment operator must return a value. The expression s2 = s1 should return s2 so it can be assigned to s3. We use the this pointer to return the calling object:
String &String::operator=( const String &other )
{
if( &other == this )
return *this;
delete buf;
length = other.length;
buf = new char[length + 1];
strcpy( buf, other.buf );
return *this;
}
This function returns a reference to the calling object. The this pointer is used in chained statements like cout << a << b << c, where the << operator returns a reference to cout, enabling the chain.
Similarly, for the Date class:
Date& Date::operator+=(int days)
{
for (int i=0; i < days; i++)
*this++;
return *this;
}
Now we can write date2 = date1 + 1 or date2 = date1++ just like with integers.
Conversions
C and C++ have rules for implicitly converting one built-in type to another in various situations:
- Assigning a value (int to long)
- Performing arithmetic (int to float before addition)
- Passing arguments to functions
- Returning values from functions
We can define conversions for our classes too. A class is a user-defined data type, and we can specify conversions between classes or between a class and a built-in type.
Conversion by Constructor: A constructor that takes only one parameter is considered a conversion function. It specifies a conversion from the parameter's type to the class type. For example, if we have a Fraction class and write f = 3, the constructor that takes a single integer is called, converting 3 into a Fraction object with numerator 3 and denominator 1.
Conversion Operators: For converting from our class to another class (especially one in a library we can't modify), we use conversion operators.
Sample Program (conversion by constructor)
The Fraction class stores a fraction as separate numerator and denominator integers, avoiding floating-point precision problems. For example, 1/3 stored as double becomes 0.33333..., and 3 * 0.33333... gives 0.99999..., not 1. The Fraction class keeps 1 and 3 as integers, so arithmetic remains exact.
The constructor provides a default value of 1 for the denominator:
Fraction::Fraction( long num, long den = 1 ) { ... }
This automatically handles conversions. When the program calculates a = b + c where b is 23/11 and c is 2/3, the addition operator uses the greatest common factor (GCF) to produce exact results:
Output: 91/33
π‘ Why this matters: Real-world applications like banking require exact arithmetic. Banks store currency as strings or separate integers, not as floating-point numbers, ensuring that 90 paisas added to 9 rupees and 10 paisas equals exactly 10 rupees and 0 paisas, not 9.999...
β Key Takeaways
To properly manage classes with dynamic memory, always define a custom assignment operator that allocates separate memory and copies content rather than pointers. Use the this pointer to check for self-assignment (the first and most important check in the assignment operator) and to return the calling object for chained assignments. Single-argument constructors serve as implicit conversion functions, allowing seamless conversion from built-in types to user-defined types. For exact arithmetic, store values as separate components (like numerator and denominator in Fraction class) to avoid floating-point precision errors found in banks and financial applications.
π§ Quick Revision Questions
- Why does the default assignment operator cause problems for classes with pointer data members that point to dynamically allocated memory?
- What is the first check that should be performed in a custom assignment operator, and why is it important?
- How does the
thispointer enable chained assignments likes3 = s2 = s1? - What is the difference between conversion by constructor (single-argument constructor) and conversion operators?
- In the Fraction class example, why does storing numerator and denominator separately prevent precision loss compared to using floating-point numbers?
π Lecture 35 β Streams
π Overview: This lecture provides a comprehensive overview of C++ streams, explaining how they function as ordered sequences of bytes for input and output operations. It covers source and destination concepts, formatted input/output, buffered versus unbuffered streams, and the member functions associated with stream objects, which are essential for managing data flow between programs and external devices.
ποΈ Topics Covered
The lecture covers streams as an ordered sequence of bytes, source and destination of streams including keyboard, screen, files, and memory, state of streams for error checking, formatted input and output capabilities, buffered versus unbuffered I/O with cout and cerr, standard predefined stream objects (cin, cout, cerr, clog), operator overloading for stream insertion and extraction, and various member functions like get(), read(), getline(), put(), write(), unget(), and peek().
π Lecture Summary
Streams
Streams are an ordered sequence of bytes that serve as a door or pipe through which a program can communicate with the outside world. There are two types: input streams (e.g., cin) and output streams (e.g., cout). The cin stream reads data from the keyboard and stores it in variables, while cout displays data on the screen.
When you press a key on the keyboard, its ASCII code (binary representation of a character) enters the computer. The cin stream performs implicit conversion, taking the character ASCII code and converting it into the appropriate number before storing it in an integer variable. The stream extractor operator (>>) of cin is heavily overloaded β it knows how to behave with int, char, float, and string data types and what sort of conversion is required.
π Definition β Stream: An ordered sequence of bytes that allows data to move from one part of the computer to another, implemented as objects with member functions and operators.
π Definition β Stream Extractor Operator (>>): The operator associated with cin that gets data from the stream and stores it into a variable; it is overloaded to handle multiple data types.
π Example: If we write cin >> i; where i is an integer, cin will take a character in ASCII code from the keyboard, convert it into a number, and store it into the integer variable. If we write cin >> c; where c is a character data type, pressing a key stores it as a character.
Source and Destination of Streams
For every stream, there must be some source and destination. For cin, the source is normally the keyboard, and the destination is typically an ordinary variable (native data type), an area in memory, or a user-defined object. For cout, the source may be a file, memory region, or a variable, and the destination is normally the screen, but can also be a file or printer.
"Every stream has an associated source and a destination"
Every stream has a state that can be checked. If bad input is entered (e.g., typing 'a' when expecting an integer), the stream signals an error and sets its state accordingly. From a program, we can always test whether the state of the stream is correct, allowing for error checking, debugging, and error handling.
π Example: When taking two integers from the keyboard, dividing one by the other, and displaying the result:
int i, j;
cin >> i;
cin >> j;
cout << i / j;
If the user enters 0 for j, we should check if j is not zero before carrying out the division.
Formatted Input and Output
Streams provide formatted input and output capabilities. We can format output so that numbers are placed correctly at the correct position, such as in electricity bills or telephone bills. Formatting allows us to specify alignment (left or right justified), decimal precision, and other presentation details. The presented representation (what humans read) can be different from the internal representation.
π‘ Why this matters: Formatting ensures output is readable and professional, like displaying matrix columns aligned properly or printing values like pi as 3.141 instead of 3.1415926.
Recap Streams
Streams are an ordered sequence of bytes that allow data to move from one part of the computer to another (screen, keyboard, memory, disk files). They are implemented as objects with member functions and heavily overloaded member operators to handle a variety of data types. Streams have a state that can be checked (e.g., eof for end of file).
The header file iostream.h must be included to use cin and cout. For formatted input and output manipulation, the header file iomanip.h is required.
Standard streams provided by default when including iostream.h include cin (input/reading), cout (output/writing), cerr (standard error), and clog (standard log).
Buffered Input/Output
Due to the speed difference between electronic components (chips, memory, microprocessor) and electro-mechanical devices (keyboard, monitor, disk), buffered input/output is used. A buffer is an area where data is gathered before being written or displayed. Instead of writing each number individually to disk (which would be inefficient), data is collected in a buffer and written in one operation.
cout is a buffered output stream β it gathers data and sends it to the screen. cerr is an unbuffered output stream β it shows data on the screen immediately when it gets it. clog is a buffered standard error stream used for logging detailed program information.
The flush command forces data from the buffer to go to its destination and makes the buffer empty.
π Example: In a program with a loop that performs complex calculations taking one minute per iteration, we need unbuffered output on the screen to see iteration numbers after every minute. Using cerr instead of cout for this purpose ensures immediate display.
π Definition β endl: When written as cout << endl;, it not only moves the cursor to the left margin of the new line but also flushes the output, making it appear as if cout is unbuffered.
Methods with Streams
Input stream (cin) methods:
- cin.get() β reads a single character from the keyboard and returns it; has two variants:
c = cin.get()andcin.get(character_variable) - cin.read() β returns a buffer instead of a single character; reads a specified number of characters into a buffer, normally up to a delimiter
- *cin.getline(char buffer, int buff_size, char delimiter = '\n') β reads a complete buffer up to the specified delimiter or number of characters; if SIZE is 100, it reads 99 characters and inserts a null character in the end
- cin.unget() β returns the most recently gotten single character
- cin.peek() β returns the next character that would be read if cin.get() were issued
Output stream (cout) methods:
- cout.put(character_variable) β outputs a single character
- cout.write() β performs raw, unformatted output of a chunk of data from the buffer
- cout.putline() β outputs a buffer (though cout itself knows how to handle character strings)
The stream insertion operator (<<) is overloaded for the output stream and returns a reference of the output stream, allowing chaining. The syntax is: ostream& ostream::operator << (char *text);
π‘ Why this matters: Chaining allows statements like cout << "The value is " << i; because the first part returns a reference to cout, which is then used for the next part.
White space is significant β cin and cout are sensitive to white space, treating it as a delimiter. When entering a name like "naveed malik" using cin >> name;, only "naveed" is stored; "malik" remains in the buffer until expected.
π Example: Using getline function:
#include <iostream.h>
int main() {
const int SIZE = 80;
char buffer[SIZE];
cout << "\n Enter a sentence: \n";
cin.getline(buffer, SIZE);
cout << " The sentence entered is: \n" << buffer << endl;
return 0;
}
Output:
Enter a sentence:
this is a test
The sentence entered is:
this is a test
π Example: Using read and write functions:
#include <iostream.h>
int main() {
const int SIZE = 80;
char buffer[SIZE];
cout << "\n Enter a sentence: \n";
cin.read(buffer, 20);
cout << " The sentence entered was: \n";
cout.write(buffer, cin.gcount());
cout << endl;
return 0;
}
Output:
Enter a sentence:
This is a sample program using read and write functions
The sentence entered was:
This is a sample pro
β Key Takeaways
Streams are ordered sequences of bytes implemented as objects that connect sources and destinations for data movement. cin handles input from the keyboard with implicit ASCII to value conversion, while cout handles output to screen with buffered behavior. The three key output streams are cout (buffered, normal output), cerr (unbuffered, immediate error display), and clog (buffered, logging). Stream operators (>> and <<) are heavily overloaded and return references to the stream object, enabling chaining. Important member functions include get() and getline() for character/line input, read() and write() for buffer handling, and put() for single character output.
π§ Quick Revision Questions
- What is a stream in C++ and what are the two main types of streams?
- How does cin handle the conversion from keyboard input to stored integer values?
- What is the difference between buffered (cout) and unbuffered (cerr) output streams?
- How does the stream insertion operator (<<) enable chaining in output statements?
- What is the purpose of the getline() function and how does it differ from the get() function?