Object Oriented Programming using C++ Notes
DSC course under University of Kerala (UoK FYUGP Regulations). Credits: 4 | 60 Hours (4 Hrs/Week).
Chapter-Wise Module Notes & PDF Downloads
Short Notes
All Modules IncludedComplete syllabus revision notes covering all modules in one single PDF
Module 1
Introduction to C++
Module 2
Classes and Objects
Module 3
Operator Overloading, Arrays & Strings
Module 4
Inheritance & Runtime Polymorphism
Module 5
File I/O and Exception Handling
Read Module Notes Online
Module I: Introduction to C++
Chapter 1: Foundations of Object-Oriented Programming
1.1 Evolution from Procedural to Object-Oriented Paradigms
Early software systems were built primarily using Procedure-Oriented Programming (POP) in languages such as C, Pascal, and FORTRAN. In POP, a problem is decomposed into a sequence of functions (procedures) that operate on shared global or local data structures. While effective for small-scale utilities, procedural architectures exhibit severe structural fragility as codebases grow beyond tens of thousands of lines. Because global data is freely accessible to any function, an unintended modification in one module can silently corrupt state relied upon by dozens of other routines. Furthermore, data structures and the functions that manipulate them are decoupled, meaning a change in a record layout forces manual updates across every function signature and body that touches that record.
Object-Oriented Programming (OOP), pioneered in Simula-67 and Smalltalk and brought into high-performance systems engineering by Bjarne Stroustrup's C++ in the early 1980s, inverts this design philosophy. Instead of treating data as passive bytes acted upon by external functions, OOP binds data and the operations permitted on that data into self-contained software units called objects. Each object guards its internal state behind a well-defined public interface, communicating with other objects through structured messages (member function calls). This alignment between software entities and real-world domain entities improves modularity, maintainability, and defect isolation.
| Architectural Dimension | Procedure-Oriented Programming (POP) | Object-Oriented Programming (OOP) |
|---|---|---|
| Primary Decomposition Unit | Functions and procedures operating sequentially on data. | Classes and objects bundling state and behavior together. |
| Design Methodology | Top-down functional decomposition from main routine to helpers. | Bottom-up and domain-driven modeling of interacting entities. |
| Data Security & Access | Global data moves openly across functions; weak access barriers. | Data is encapsulated as private; accessible only via public methods. |
| Code Extensibility | Adding new data variants requires editing existing switch/if logic. | Inheritance and polymorphism extend behavior without modifying base code. |
| Representative Languages | C, Pascal, COBOL, early FORTRAN. | C++, Java, C#, Python, Smalltalk. |
1.2 Characteristics and Applications of OOP
Object-oriented systems exhibit distinct engineering characteristics that make them suitable for large-scale software:
- Data-Centric Modularity: Emphasis is placed on modeling domain data and invariants first rather than control-flow steps alone.
- Information Hiding: Internal implementation details (such as whether a stack uses a fixed array or a linked list) are hidden from client code, allowing internal refactoring without breaking callers.
- Extensibility via Reuse: Tested classes can be reused through composition (embedding objects) or inheritance (deriving specialized classes), reducing duplication and testing overhead.
- Message-Passing Architecture: Objects collaborate by invoking each other's public member functions, keeping coupling loose and interfaces explicit.
- Elimination of Redundant Logic: Shared behaviors reside once in a base class rather than being copy-pasted across independent modules.
Because C++ combines zero-overhead hardware access with high-level OOP abstractions, it powers mission-critical domains including operating system kernels and device drivers, real-time 3D game engines (Unreal Engine), relational database engines (MySQL, PostgreSQL components), high-frequency financial trading platforms, embedded firmware, web browser rendering engines (Chromium Blink), CAD/CAM modeling suites, and scientific simulation toolkits.
1.3 Core OOP Concepts
Six foundational pillars define the object-oriented model in C++:
- Object: A concrete runtime instance of a class occupying memory and possessing a unique identity, a set of attribute values (state), and executable operations (behavior). For example,
student1andstudent2are distinct objects of classStudent. - Class: A user-defined blueprint or template that specifies the data members (attributes) and member functions (methods) common to all objects of that category. A class declaration itself consumes no runtime object memory until instantiated.
- Data Abstraction: The practice of exposing only essential external features and behaviors while suppressing background implementation complexity. When a programmer calls
account.withdraw(500), they rely on the abstract contract without needing to know how ledger validation or disk logging executes internally. - Data Encapsulation: The mechanism of bundling data members and member functions inside a single class boundary and restricting direct external access via access specifiers (
private,protected,public). Encapsulation enforces class invariants—for instance, ensuring aBankAccountbalance cannot become negative through arbitrary external assignment. - Inheritance: The mechanism by which a new class (derived or child class) acquires properties and behaviors from an existing class (base or parent class), establishing an "is-a" hierarchy and enabling hierarchical code reuse.
- Polymorphism: Literally "many forms"—the ability of a single function name, operator, or base-class interface to exhibit different behaviors depending on the argument types or the runtime type of the target object. C++ supports compile-time polymorphism (function overloading, operator overloading, templates) and runtime polymorphism (virtual functions).
To see these six concepts working together, consider a university library management system. A LibraryItem class defines abstract attributes such as itemId and title while encapsulating isCheckedOut as private so external code cannot toggle availability without logging a borrower. Derived classes Book and Journal inherit common metadata from LibraryItem while adding ISBN or volume numbers. Finally, a polymorphic calculateLateFee(int days) interface computes different daily rates depending on whether the runtime object is a Book or a Journal.
Chapter 2: Basic C++ Program Structure, Data Types, and Streams
2.1 Anatomy of a C++ Program and Compilation Pipeline
A standard C++ source file (typically saved with extension .cpp, .cc, or .cxx) follows a structured organization consisting of preprocessor directives, namespace declarations, optional class or function prototypes, the mandatory main() entry point, and supporting definitions. Unlike C, C++ enforces strict type checking, requires function prototypes before calls, and places standard library components inside the std namespace to prevent naming collisions.
Transforming C++ source code into an executable binary occurs in four stages: (1) Preprocessing expands #include headers, substitutes #define macros, and strips comments; (2) Compilation parses syntax, validates static types, performs template instantiation, and emits assembly code; (3) Assembly translates mnemonics into machine object files (.o or .obj); and (4) Linking resolves external symbols against the C++ Standard Library to produce the final executable.
#include <iostream> // Standard input/output stream definitions
#include <iomanip> // Stream manipulators such as setw and setprecision
using namespace std; // Brings std symbols into current scope
namespace Physics {
const double GRAVITY = 9.80665;
}
const double PI = 3.14159265; // Typed compile-time constant
int main() {
double radius = 0.0;
cout << "Enter circle radius: ";
cin >> radius;
double area = PI * radius * radius;
double circumference = 2.0 * PI * radius;
cout << fixed << setprecision(2);
cout << left << setw(16) << "Metric" << right << setw(10) << "Value" << endl;
cout << left << setw(16) << "Radius" << right << setw(10) << radius << endl;
cout << left << setw(16) << "Area" << right << setw(10) << area << endl;
cout << left << setw(16) << "Circumference" << right << setw(10) << circumference << endl;
cout << "Gravity (NS): " << Physics::GRAVITY << endl;
return 0; // Indicates normal termination to the OS
}Key structural elements in Listing 1.1 include:
- Preprocessor Directives (
#include): Instruct the preprocessor to include header contents before compilation. Standard C++ headers omit the.hsuffix (e.g.,<iostream>,<string>,<fstream>). - Namespaces and Scope Resolution (
::): A namespace partitions global identifiers. Withoutusing namespace std;, standard objects must be qualified explicitly asstd::cout,std::cin, andstd::endl—a practice preferred in large multi-library headers to avoid name clashes. int main()Function: Every hosted C++ program begins execution atmain()and returns an integer exit code (0signals success).- Comments: C++ supports single-line comments (
// ...) and multi-line block comments (/* ... */).
2.2 Keywords, Identifiers, Variables, References, and Constants
Keywords are reserved identifiers with fixed syntactic meaning that cannot be repurposed as variable or class names. C++ inherits C keywords (int, if, else, for, while, switch, return, struct, const, sizeof) and adds OOP and type-system keywords including class, public, private, protected, friend, virtual, inline, operator, this, new, delete, try, throw, catch, namespace, using, bool, true, and false.
Identifiers name variables, functions, classes, and objects. Valid identifiers contain letters (A-Z, a-z), digits (0-9), and underscores (_), must begin with a letter or underscore, are strictly case-sensitive, and cannot contain spaces or punctuation. A variable is a named memory location whose value can change during execution; C++ permits declaring variables anywhere before first use. A reference variable (int& ref = count;) creates an alias to an existing variable; it must be initialized upon declaration and cannot be rebound to another variable later. A constant locks its value against modification after initialization using const (type-checked, scoped constant) or constexpr (guaranteed compile-time constant expression), which are strongly preferred over untyped #define macros.
2.3 Basic Data Types and Memory Representation
C++ provides fundamental built-in types categorized into integral, floating-point, Boolean, character, and valueless (void) types, adjustable with modifiers signed, unsigned, short, and long. For an integer representation occupying n bits, the representable value intervals are governed by binary two's complement arithmetic:
8 * sizeof(type); Runsigned = non-negative integer range; Rsigned = two's complement signed integer range. For a 16-bit short (n = 16), signed values span -32,768 to +32,767.| Data Type | Typical Size | Approximate Range / Precision | Primary Use Case |
|---|---|---|---|
bool |
1 byte | false (0) or true (1) |
Logical predicates, flags, loop guards. |
char |
1 byte | -128 to 127 (signed) or 0 to 255 (unsigned) | Single ASCII characters and raw byte buffers. |
short int |
2 bytes | -32,768 to +32,767 | Memory-constrained small integer counters. |
int |
4 bytes | -2,147,483,648 to +2,147,483,647 | General-purpose whole-number arithmetic and indices. |
long long |
8 bytes | -9.22 × 1018 to +9.22 × 1018 | Large integer totals, timestamps, combinatorics. |
float |
4 bytes | ±3.4 × 1038 (~6–7 decimal digits) | Single-precision graphics and sensor values. |
double |
8 bytes | ±1.7 × 10308 (~15 decimal digits) | Standard scientific and financial floating-point math. |
void |
0 bytes | No value set | Functions returning no value; generic void* pointers. |
2.4 Streams in C++, Type Casting, and Operators
C++ models I/O as a sequence of bytes flowing through streams rather than format-string functions. The <iostream> header predefines four standard stream objects connected to the console:
cout(Standard Output): Buffered output stream connected to the display, used with the insertion operator (<<).cin(Standard Input): Buffered input stream connected to the keyboard, used with the extraction operator (>>), which skips leading whitespace and parses tokens according to the target variable's type.cerr(Unbuffered Error): Sends diagnostic error messages immediately to the error device without waiting for buffer flushing.clog(Buffered Error): Buffered error stream suitable for high-volume logging.
C++ supports a rich operator set: arithmetic (+, -, *, /, %), relational (==, !=, <, >, <=, >=), logical (&&, ||, !), bitwise (&, |, ^, ~, <<, >>), assignment/compound (=, +=, -=, *=, /=), increment/decrement (++, --), ternary conditional (?:), and C++-specific operators including scope resolution (::), memory allocation (new, delete), and member access (., ->). Note that logical && and || perform short-circuit evaluation: if the left operand determines the outcome, the right operand is not evaluated.
| Precedence Tier | Operators | Associativity | Notes |
|---|---|---|---|
| Highest (1) | :: |
Left-to-right | Global or class scope resolution. |
| Postfix (2) | (), [], ., ->, ++, -- |
Left-to-right | Function call, subscript, member access, postfix inc/dec. |
| Unary (3) | ++, --, !, ~, -, *, &, sizeof, new, delete |
Right-to-left | Prefix operators, dereference, address-of, dynamic allocation. |
| Multiplicative & Additive (4–5) | *, /, % then +, - |
Left-to-right | Integer division truncates fractional parts. |
| Relational & Equality (6–7) | <, <=, >, >= then ==, != |
Left-to-right | Evaluate to bool (true or false). |
| Logical & Assignment (8–9) | &&, ||, ?:, =, +=, -= |
&&/|| L-to-R; ?:/= R-to-L |
Chained assignment a = b = 0 evaluates right-to-left. |
Chapter 3: Decision, Loop, and Jump Control Structures
3.1 Decision Structures: if, if-else, and switch
Control structures alter sequential execution based on runtime conditions. The if statement executes a block only when its Boolean condition evaluates to non-zero (true). The if-else construct provides mutually exclusive two-way branching, while an else if ladder chains multiple conditions sequentially. Nested if statements place a decision inside another decision branch; proper braces { } prevent the "dangling else" ambiguity where an else binds to the nearest unmatched if.
The switch statement dispatches execution among multiple constant integral or enumeration cases (int, char, enum) based on a single selector expression. Each case label ends with break to prevent unintended fall-through into subsequent cases, and an optional default branch handles unmatched values. Unlike if-else ladders, switch cannot evaluate floating-point ranges or string comparisons directly.
#include <iostream>
using namespace std;
int main() {
int marks = 0;
cout << "Enter marks (0-100): ";
cin >> marks;
char grade = 'F';
if (marks < 0 || marks > 100) {
cout << "Invalid marks entered.\n";
return 1;
} else if (marks >= 90) {
grade = 'O';
} else if (marks >= 80) {
grade = 'A';
} else if (marks >= 70) {
grade = 'B';
} else if (marks >= 60) {
grade = 'C';
} else if (marks >= 40) {
grade = 'P';
} else {
grade = 'F';
}
cout << "Grade: " << grade << " -> ";
switch (grade) {
case 'O': cout << "Outstanding\n"; break;
case 'A': cout << "Excellent\n"; break;
case 'B': cout << "Very Good\n"; break;
case 'C': cout << "Good\n"; break;
case 'P': cout << "Pass\n"; break;
default: cout << "Fail (Reappear required)\n"; break;
}
return 0;
}3.2 Loop Constructs: while, do-while, and for
Iteration repeats a statement block while a continuation condition holds. Choosing the right loop depends on whether iteration count is known beforehand and whether at least one execution is mandatory:
whileLoop (Entry-Controlled): Evaluates the condition before the first iteration; if initially false, the body executes zero times. Ideal for sentinel-controlled input loops and stream reading.do-whileLoop (Exit-Controlled): Executes the body once before testing the condition, guaranteeing at least one execution. Always terminated by a semicolon afterwhile (condition);. Ideal for interactive menus and input validation.forLoop (Entry-Controlled Counter): Consolidates initialization, continuation condition, and update expression into a compact headerfor (init; cond; update), making fixed-count, matrix, and array-traversal loops clear and less error-prone. Nestedforloops drive 2D grids and pattern generation.
| Loop Feature | while |
do-while |
for |
|---|---|---|---|
| Condition Check Timing | Entry-controlled (top of loop) | Exit-controlled (bottom of loop) | Entry-controlled (top of loop) |
| Minimum Executions | 0 times (if condition initially false) | 1 time (guaranteed) | 0 times (if condition initially false) |
| Trailing Semicolon | None on header | Mandatory after while (cond); |
None on header |
| Primary Use Case | Event/sentinel-driven loops | Menu prompts and validation | Fixed-count & index-based loops |
3.3 Jump Statements: break, continue, and goto
Jump statements transfer control unconditionally:
break: Immediately terminates the innermost enclosing loop (for,while,do-while) orswitchstatement and resumes execution at the statement following it.continue: Skips the remainder of the current loop iteration and jumps directly to the next iteration test (infor, executes the update expression first).goto: Jumps unconditionally to a labeled statement within the same function (label:). While useful in rare cases to break out of deeply nested loops, indiscriminategotousage creates unstructured "spaghetti code" and bypasses variable initializations; structured loops and functions are preferred.
#include <iostream>
using namespace std;
int main() {
int choice = 0;
do {
cout << "\n1. Prime Check 2. Factorial 3. Fibonacci 4. Exit\nChoice: ";
cin >> choice;
if (choice == 4) {
break; // Exit do-while loop immediately
}
if (choice < 1 || choice > 4) {
cout << "Invalid option. Try again.\n";
continue; // Skip rest of iteration and re-prompt
}
int n = 0;
cout << "Enter positive integer: ";
cin >> n;
if (n <= 0) goto invalid_input;
if (choice == 1) {
bool isPrime = (n > 1);
for (int d = 2; d * d <= n; ++d) {
if (n % d == 0) {
isPrime = false;
break;
}
}
cout << n << (isPrime ? " is Prime\n" : " is Not Prime\n");
} else if (choice == 2) {
long long fact = 1;
int i = 1;
while (i <= n) {
fact *= i;
++i;
}
cout << "Factorial(" << n << ") = " << fact << "\n";
} else {
long long a = 0, b = 1;
cout << "Fibonacci: ";
for (int i = 0; i < n; ++i) {
cout << a << " ";
long long next = a + b;
a = b;
b = next;
}
cout << "\n";
}
continue;
invalid_input:
cout << "Error: Input must be strictly positive.\n";
} while (true);
return 0;
}3.4 Dynamic Memory Allocation Preview: new and delete
While local variables live on the automatic call stack with fixed compile-time sizes, C++ allocates runtime-sized memory on the heap (free store) using the type-safe new operator and releases it using delete (or new[] paired with delete[] for arrays). Unlike C's malloc(), new automatically computes byte size, returns a typed pointer without casting, and invokes class constructors; similarly, delete invokes class destructors before freeing memory.
3.5 Type Conversions, Scope Resolution, and C++ vs C Summary
C++ performs implicit arithmetic conversions (promoting narrower integral types like char and short to int, and promoting int to double in mixed expressions) and provides four explicit named cast operators that replace unsafe C-style casts: static_cast<T>(expr) for well-defined compile-time conversions (such as static_cast<double>(sum) / count), const_cast<T>(expr) to add or remove const qualification, dynamic_cast<T>(expr) for runtime-checked polymorphic downcasting, and reinterpret_cast<T>(expr) for low-level byte-pointer reinterpretation in binary file I/O.
The scope resolution operator (::) also resolves variable shadowing when a local variable shares the same identifier as a global variable: writing ::value inside a function accesses the global value while value refers to the local variable.
| Language Feature | C Language (Procedural) | C++ Language (Multi-Paradigm OOP) |
|---|---|---|
| Programming Paradigm | Strictly procedural (functions + structs). | Multi-paradigm: procedural, object-oriented, and generic. |
| Data Protection | No access specifiers; struct fields are always public. | private, protected, and public encapsulation. |
| Console I/O | Format-string functions printf() / scanf(). |
Type-safe extensible streams cout << / cin >>. |
| Function Overloading | Not supported; every function name must be unique. | Supported via parameter-type name mangling. |
| Reference Variables | Only pointers (*) exist. |
Supports both pointers and safe non-null aliases (&). |
| Heap Management | malloc() / calloc() and free(). |
new / new[] and delete / delete[] with constructors. |
| Error Handling | Return codes and global errno. |
Structured try / throw / catch exceptions. |
#include <iostream>
#include <iomanip>
using namespace std;
int counter = 100; // Global variable
int main() {
int counter = 25; // Shadows global counter
int& alias = counter; // Reference bound to local counter
alias += 5;
cout << "Local counter (via alias): " << counter << endl;
cout << "Global counter (via ::): " << ::counter << endl;
int totalMarks = 427, subjects = 5;
double average = static_cast<double>(totalMarks) / subjects;
cout << fixed << setprecision(2);
cout << "Average Marks: " << average << "%" << endl;
return 0;
}3.6 Applied Control-Flow Walkthrough: Armstrong Numbers and Nested Pattern Loops
Combining for, while, and conditional branching solves classic numerical problems cleanly. An Armstrong (narcissistic) number of d digits equals the sum of its digits each raised to the d-th power—for example, 153 = 13 + 53 + 33. Similarly, nested for loops allow an outer loop to iterate across rows while an inner loop prints columns, forming symmetric numeric pyramids and multiplication matrices.
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
cout << "3-Digit Armstrong Numbers: ";
for (int num = 100; num <= 999; ++num) {
int temp = num, sum = 0;
while (temp > 0) {
int digit = temp % 10;
sum += digit * digit * digit;
temp /= 10;
}
if (sum == num) cout << num << " ";
}
cout << "\n\n4x4 Multiplication Table:\n";
for (int row = 1; row <= 4; ++row) {
for (int col = 1; col <= 4; ++col) {
cout << setw(4) << (row * col);
}
cout << endl;
}
return 0;
}Module II: Classes and Objects
Chapter 4: Classes, Objects, and Access Control
4.1 Declaration of Classes and Object Instantiation
In C++, a class is a user-defined composite type declared with the class keyword, terminated by a mandatory semicolon };. A class groups data members (variables representing state) and member functions (methods operating on that state) under explicit access specifiers:
private: The default access level in aclass. Members are accessible only to member functions of the same class and declaredfriendfunctions or classes.public: Members form the external interface accessible from any function in scope via the dot operator (obj.method()) or arrow operator (ptr->method()).protected: Accessible within the class itself, its friends, and derived classes (explored in Module IV).
Member functions may be defined inside the class body (implicitly treated as inline requests) or declared inside the class and defined outside using the scope resolution operator (ClassName::funcName). Defining non-trivial methods outside the class keeps the class interface concise and separates specification from implementation. By contrast, a C++ struct is identical to a class except that its default member access and default inheritance mode are public rather than private.
#include <iostream>
#include <string>
using namespace std;
class BankAccount {
private:
int accountNo;
string holderName;
double balance;
public:
void openAccount(int no, const string& name, double initial);
void deposit(double amount);
bool withdraw(double amount);
void display() const; // const member function cannot modify state
};
void BankAccount::openAccount(int no, const string& name, double initial) {
accountNo = no;
holderName = name;
balance = (initial >= 0.0) ? initial : 0.0;
}
void BankAccount::deposit(double amount) {
if (amount > 0.0) balance += amount;
}
bool BankAccount::withdraw(double amount) {
if (amount > 0.0 && amount <= balance) {
balance -= amount;
return true;
}
return false;
}
void BankAccount::display() const {
cout << "Acc #" << accountNo << " [" << holderName
<< "] Balance: Rs. " << balance << endl;
}
int main() {
BankAccount acc1, acc2; // Two distinct objects instantiated
acc1.openAccount(1001, "Ananya Nair", 5000.0);
acc2.openAccount(1002, "Rohan Menon", 2500.0);
acc1.deposit(1500.0);
acc2.withdraw(500.0);
acc1.display();
acc2.display();
return 0;
}Each object receives its own separate copy of non-static data members in memory, while all objects of the same class share a single compiled copy of the member functions in the code segment. Declaring a member function with trailing const (such as void display() const) guarantees that the method will not mutate any non-static data member, allowing it to be called on const objects.
4.2 Static Data Members and Static Member Functions
When a data member is declared static inside a class, only one shared copy exists for the entire class regardless of how many objects are created (even zero objects). Because a static member is not part of individual object memory, it must be defined and initialized once outside the class using scope resolution (e.g., int Student::totalCount = 0;). A static member function can be called using the class name directly (Student::getCount()) without an object, and it may access only static data members and other static functions because it has no this pointer.
#include <iostream>
#include <string>
using namespace std;
class Student {
private:
int rollNo;
string name;
double gpa;
static int totalStudents; // Shared across all Student objects
public:
Student(int r = 0, const string& n = "Unknown", double g = 0.0)
: rollNo(r), name(n), gpa(g) {
++totalStudents;
}
static int getCount() {
return totalStudents; // No 'this' pointer in static method
}
// Passing object by const reference and returning object by value
Student higherGpa(const Student& other) const {
return (this->gpa >= other.gpa) ? *this : other;
}
void print() const {
cout << rollNo << " - " << name << " (GPA: " << gpa << ")\n";
}
};
int Student::totalStudents = 0; // Mandatory external definition
int main() {
Student s1(1, "Meera", 8.9);
Student s2(2, "Arjun", 9.3);
Student topper = s1.higherGpa(s2);
cout << "Total instantiated: " << Student::getCount() << endl;
cout << "Higher GPA: ";
topper.print();
return 0;
}Chapter 5: Functions, Argument Passing, Inline, and Overloading
5.1 Components of a C++ Function and Argument Passing
Every C++ function comprises three components: a function prototype (declaration) specifying return type, name, and parameter types; a function definition containing the executable body; and a function call passing actual arguments to formal parameters. C++ provides three parameter-passing mechanisms:
| Mechanism | Syntax Example | Memory & Aliasing Behavior | Best Application |
|---|---|---|---|
| Pass by Value | void f(int x) |
Copies argument value into a new stack parameter; caller variable is isolated. | Small primitive inputs that must not be altered. |
| Pass by Reference | void f(int& x) |
Creates an alias to the caller's variable; zero copy overhead; changes affect caller. | Mutating caller variables (swap) or passing large objects via const T&. |
| Pass by Pointer | void f(int* p) |
Copies the memory address; requires dereferencing (*p); supports nullptr. |
Optional parameters, C-style arrays, dynamic memory handles. |
C++ also supports default arguments specified strictly from right to left in the function prototype (e.g., double interest(double p, double r = 0.05, int t = 1)), allowing callers to omit trailing arguments when standard defaults apply. Combining default arguments with function overloading must be done carefully to avoid ambiguous call errors when omitted parameters make two signatures indistinguishable.
5.2 Inline Functions and Function Overloading
Calling a tiny function (such as a one-line getter or squaring helper) incurs stack-frame setup, argument pushing, jump, and return overhead. Prefixing a function with inline advises the compiler to substitute the function's compiled instructions directly at each call site, eliminating call overhead while retaining full type safety (unlike preprocessor #define macros, which can suffer double-evaluation bugs such as SQUARE(i++)). Note that inline is a compiler hint; compilers may decline inlining for recursive functions, large loops, or functions invoked via function pointers.
Function overloading implements compile-time polymorphism by allowing multiple functions in the same scope to share an identical name provided their parameter lists differ in number of parameters, parameter data types, or parameter type order. The return type alone cannot distinguish overloaded functions because callers may ignore return values. The compiler performs name mangling (encoding parameter types into internal linker symbols) and resolves the exact match during compilation via a strict resolution hierarchy: (1) exact type match, (2) trivial/promotion conversion (char to int, float to double), (3) standard conversion (int to double), and (4) user-defined conversion.
#include <iostream>
using namespace std;
inline int square(int x) { return x * x; }
void swapValues(int& a, int& b) {
int temp = a;
a = b;
b = temp;
}
double simpleInterest(double principal, double rate = 0.07, int years = 1) {
return principal * rate * years;
}
// Overloaded area() functions
double area(double radius) {
return 3.14159 * radius * radius;
}
double area(double length, double breadth) {
return length * breadth;
}
int area(int side) {
return square(side);
}
int main() {
int x = 10, y = 25;
swapValues(x, y);
cout << "After swap: x=" << x << ", y=" << y << endl;
cout << "Default interest: " << simpleInterest(10000.0) << endl;
cout << "Custom interest: " << simpleInterest(10000.0, 0.08, 3) << endl;
cout << "Circle area: " << area(5.0) << endl;
cout << "Rectangle area: " << area(4.0, 6.5) << endl;
cout << "Square area: " << area(7) << endl;
return 0;
}Chapter 6: Friend Functions, Constructors, and Destructors
6.1 Friend Functions and Friend Classes
Strict encapsulation forbids external functions from reading private members. However, certain operations—such as binary operator overloading or bridging two tightly coupled classes—require direct access to private internals of one or more classes. C++ addresses this via the friend declaration inside the granting class:
- Global Friend Function: A non-member function declared inside a class with
friendcan access allprivateandprotectedmembers of that class using an object parameter. - Member Function as Friend: A specific method of Class A can be granted friendship by Class B (
friend void ClassA::inspect(const ClassB&);), limiting privilege to that single method. - Friend Class: Declaring
friend class Auditor;insideAccountgrants every member function ofAuditorfull access toAccount's private members.
Friendship obeys three strict rules: it is not mutual (if A is a friend of B, B is not automatically a friend of A), not transitive (friend of a friend has no special access), and not inherited by derived classes. Because friendship is granted by the target class itself inside its own definition, it preserves controlled encapsulation rather than breaking it arbitrarily.
#include <iostream>
using namespace std;
class Matrix; // Forward declaration
class Vector {
private:
int v[2];
public:
Vector(int a, int b) { v[0] = a; v[1] = b; }
friend void multiply(const Matrix& m, const Vector& vec);
friend class Inspector; // Inspector has full access to Vector
};
class Matrix {
private:
int m[2][2];
public:
Matrix(int a, int b, int c, int d) {
m[0][0] = a; m[0][1] = b;
m[1][0] = c; m[1][1] = d;
}
friend void multiply(const Matrix& m, const Vector& vec);
};
void multiply(const Matrix& mat, const Vector& vec) {
int r0 = mat.m[0][0] * vec.v[0] + mat.m[0][1] * vec.v[1];
int r1 = mat.m[1][0] * vec.v[0] + mat.m[1][1] * vec.v[1];
cout << "Product Vector: [" << r0 << ", " << r1 << "]\n";
}
class Inspector {
public:
void showVector(const Vector& vec) const {
cout << "Private Vector: (" << vec.v[0] << ", " << vec.v[1] << ")\n";
}
};
int main() {
Matrix M(1, 2, 3, 4);
Vector V(5, 6);
multiply(M, V);
Inspector insp;
insp.showVector(V);
return 0;
}6.2 Constructors: Default, Parameterized, and Copy
A constructor is a special member function sharing the exact name of its class, having no return type (not even void), and invoked automatically whenever an object is instantiated to guarantee valid initial state. Constructors may be overloaded:
- Default Constructor: Takes zero parameters (or all parameters have default values). If a programmer defines no constructors at all, the compiler synthesizes a trivial default constructor; once any custom constructor is written, the compiler stops synthesizing the implicit default constructor unless explicitly requested.
- Parameterized Constructor: Accepts arguments at object creation time (e.g.,
Box b(10, 20, 30);) and initializes members, ideally via a member initializer list (: len(l), wid(w)). Member initializer lists are mandatory for initializingconstdata members, reference members, and base-class sub-objects. - Copy Constructor: Has signature
ClassName(const ClassName& other)and initializes a new object as a copy of an existing object (triggered duringBox b2 = b1;, pass-by-value, or return-by-value). Notice the parameter must be passed by reference (const ClassName&); passing by value would recursively invoke the copy constructor infinitely.
When a class owns dynamic heap memory via raw pointers, a user-defined copy constructor must perform a deep copy (allocating fresh memory and copying contents) rather than relying on the compiler's default shallow copy (which copies only the pointer address, causing two objects to share the same heap block and triggering double-free memory corruption when both destructors execute).
| Comparison Dimension | Shallow Copy (Compiler Default) | Deep Copy (User-Defined) |
|---|---|---|
| Pointer Member Handling | Copies raw memory address; both objects point to same heap block. | Allocates a distinct heap buffer and copies underlying elements. |
| Mutation Isolation | Modifying one object's buffer silently alters the other object. | Each object owns independent memory; mutations are isolated. |
| Destructor Safety | Double-free crash when second object calls delete[] on freed address. |
Safe; each destructor frees its own non-overlapping allocation. |
6.3 Destructors and Lifecycle Constraints
A destructor is a special member function prefixed by a tilde (~ClassName()) that takes no arguments, has no return type, and cannot be overloaded (a class has at most one destructor). It executes automatically when an automatic object leaves scope, when delete is called on a heap object, or when a program terminates for static/global objects. Destructors release acquired resources such as dynamic arrays (delete[]), file handles, or network sockets.
Key constraints on constructors and destructors include: they must be declared in the public section to allow external instantiation (making a constructor private restricts creation to friends or static factory methods like Singleton); they cannot be declared const, static, or volatile; their addresses cannot be taken; constructors cannot be virtual (though destructors in base classes should be virtual); and local objects in a block are destroyed in the exact reverse order of their construction (LIFO).
#include <iostream>
#include <cstring>
using namespace std;
class Buffer {
private:
char* data;
int size;
const int id;
public:
// Parameterized constructor with member initializer list
Buffer(int bufId, const char* text = "") : id(bufId) {
size = strlen(text);
data = new char[size + 1];
strcpy(data, text);
cout << "Constructed #" << id << ": " << data << endl;
}
// Deep-copy constructor
Buffer(const Buffer& other) : id(other.id + 100) {
size = other.size;
data = new char[size + 1];
strcpy(data, other.data);
cout << "Deep-copied #" << id << ": " << data << endl;
}
// Destructor releases heap allocation
~Buffer() {
cout << "Destroying #" << id << ": " << data << endl;
delete[] data;
}
friend void printLength(const Buffer& buf);
};
void printLength(const Buffer& buf) {
cout << "Buffer #" << buf.id << " length = " << buf.size << endl;
}
int main() {
Buffer b1(1, "Kerala");
Buffer b2 = b1; // Invokes copy constructor (b2 gets id 101)
printLength(b2);
return 0; // b2 (#101) destroyed first, then b1 (#1)
}6.4 Arrays of Objects and Dynamic Object Lifecycle
Just like primitive arrays, a program can declare an array of objects such as Book catalog[50]; or allocate an array dynamically on the heap using Book* ptr = new Book[n];. When an array of n objects is created without explicit initializer arguments, the class must provide an accessible default constructor, which C++ invokes once for each element from index 0 to n - 1. When the array leaves scope or is freed with delete[] ptr;, the destructor runs in reverse order from index n - 1 down to 0. Notice that omitting the brackets (writing delete ptr; instead of delete[] ptr;) results in an incomplete teardown where only the first element's destructor executes.
To prevent unintended implicit single-argument conversions (for instance, passing an integer 5 where a Buffer object is expected), single-parameter constructors can be marked explicit: explicit Buffer(int capacity);. An explicit constructor still permits direct initialization (Buffer b(5);) while rejecting silent copy-initialization (Buffer b = 5;).
#include <iostream>
#include <string>
using namespace std;
class Product {
private:
int code;
string title;
double price;
public:
Product() : code(0), title("Unassigned"), price(0.0) {}
Product(int c, const string& t, double p) : code(c), title(t), price(p) {}
void setDetails(int c, const string& t, double p) {
code = c;
title = t;
price = p;
}
double getPrice() const { return price; }
void show() const {
cout << "[" << code << "] " << title << " - Rs. " << price << endl;
}
};
int main() {
const int N = 3;
Product* inventory = new Product[N]; // Invokes default constructor 3 times
inventory[0].setDetails(101, "Keyboard", 1250.0);
inventory[1].setDetails(102, "Optical Mouse", 650.0);
inventory[2].setDetails(103, "USB-C Hub", 1800.0);
double total = 0.0;
for (int i = 0; i < N; ++i) {
inventory[i].show();
total += inventory[i].getPrice();
}
cout << "Total Inventory Value: Rs. " << total << endl;
delete[] inventory; // Destroys all 3 objects in reverse order
return 0;
}| Lifecycle Event | Constructor / Destructor Invoked | Key Rule or Constraint |
|---|---|---|
ClassName obj; |
Default Constructor | Must exist if no other constructors or if explicit default provided. |
ClassName obj(a, b); |
Parameterized Constructor | Initializes const and reference members via initializer list. |
ClassName b = a; |
Copy Constructor | Takes const ClassName&; must deep-copy raw heap pointers. |
ClassName arr[5]; |
Default Constructor × 5 | Runs sequentially from index 0 to 4. |
Scope exit / delete |
Destructor (~ClassName()) |
Zero parameters, no return type, cannot be overloaded; runs LIFO. |
6.5 Applied Case Study: Dynamic Stack Class with Encapsulation and Rule of Three
To unify class encapsulation, parameterized constructors, deep-copy constructors, const member functions, and destructors, Listing 2.7 implements a heap-backed IntStack. By storing capacity, top, and a dynamic int* data array as private members, external callers cannot corrupt the stack pointer directly. Notice how the destructor frees data, while the copy constructor allocates an independent array so copying a stack never creates dangling aliases.
#include <iostream>
using namespace std;
class IntStack {
private:
int* data;
int capacity;
int topIndex;
public:
IntStack(int cap = 8) : capacity(cap > 0 ? cap : 8), topIndex(-1) {
data = new int[capacity];
}
// Deep-copy constructor
IntStack(const IntStack& other)
: capacity(other.capacity), topIndex(other.topIndex) {
data = new int[capacity];
for (int i = 0; i <= topIndex; ++i) {
data[i] = other.data[i];
}
}
~IntStack() {
delete[] data;
}
bool push(int val) {
if (topIndex >= capacity - 1) return false;
data[++topIndex] = val;
return true;
}
bool pop(int& outVal) {
if (topIndex < 0) return false;
outVal = data[topIndex--];
return true;
}
bool isEmpty() const { return topIndex < 0; }
int size() const { return topIndex + 1; }
};
int main() {
IntStack s1(4);
s1.push(10);
s1.push(20);
s1.push(30);
IntStack s2 = s1; // Independent deep copy
int popped = 0;
while (s2.pop(popped)) {
cout << "Popped from copy: " << popped << endl;
}
cout << "Original stack size remains: " << s1.size() << endl;
return 0;
}Module III: Operator Overloading, Arrays & Strings
Chapter 7: Operator Overloading Fundamentals
7.1 Concept of Operator Overloading and the operator Keyword
Built-in operators such as +, -, *, and == work natively on primitive types like int and double, yet fail on user-defined class types unless explicitly taught how to behave. Operator overloading is a form of compile-time polymorphism that assigns additional, domain-appropriate semantics to existing C++ operators when applied to class objects. For instance, adding two Complex numbers via c3 = c1 + c2 or comparing two String objects via s1 == s2 reads far more naturally than c3 = c1.add(c2).
To overload an operator, C++ defines a special function named using the operator keyword immediately followed by the operator symbol—for example, operator+, operator++, or operator==. This function may be implemented either as a non-static member function of the class or as a non-member (typically friend) function. Regardless of implementation style, operator overloading obeys five invariant language rules:
- Existing Symbols Only: Only valid built-in C++ operators may be overloaded; programmers cannot invent new operator tokens such as
**or@. - Preserved Arity and Precedence: Overloading cannot alter the number of operands an operator takes (unary remains unary, binary remains binary) nor its precedence or associativity in the expression grammar.
- At Least One User-Defined Operand: An overloaded operator must accept at least one parameter of class or enumeration type; redefining
int + intis illegal. - No Default Arguments: Overloaded operator functions (except
operator()) cannot specify default parameter values. - Non-Overloadable Operators: Five operators cannot be overloaded because their semantics are tied to compile-time resolution or object identity: scope resolution (
::), member selection (.), pointer-to-member selection (.*), ternary conditional (?:), andsizeof(along withtypeid).
| Non-Overloadable Operator | Reason Prohibited in C++ |
|---|---|
:: (Scope Resolution) |
Operates on compile-time namespaces and class names, not runtime object values. |
. (Direct Member Access) |
Always accesses a physical member name of a class/struct; overloading would break member lookup. |
.* (Pointer-to-Member) |
Tied directly to compile-time member offset resolution. |
?: (Ternary Conditional) |
Guarantees short-circuit evaluation of only the selected branch, which function calls cannot preserve. |
sizeof |
Evaluated at compile time based on static type layout in bytes. |
7.2 Overloading Unary Operators: Member vs Friend, Prefix vs Postfix
A unary operator acts on a single operand (such as unary negation -v, logical NOT !flag, or increment/decrement ++c and c++). When overloaded as a member function, the target object is passed implicitly via the this pointer, so the function takes zero explicit parameters. When overloaded as a friend function, the target object must be passed explicitly as one parameter (by reference if mutated, such as friend Counter& operator++(Counter& c);).
To distinguish prefix increment (++obj) from postfix increment (obj++), C++ uses a syntactic marker: the postfix version accepts a dummy unnamed int parameter (operator++(int)). Prefix returns a reference (ClassName&) to the already-incremented object (enabling chaining and avoiding a copy), whereas postfix saves a temporary copy of the original state, increments the object, and returns the saved copy by value.
#include <iostream>
using namespace std;
class Counter {
private:
int count;
public:
Counter(int c = 0) : count(c) {}
// Unary minus (-) returns negated copy
Counter operator-() const {
return Counter(-count);
}
// Unary logical NOT (!) tests whether counter is zero
bool operator!() const {
return count == 0;
}
// Prefix ++: increments first, returns reference
Counter& operator++() {
++count;
return *this;
}
// Postfix ++: dummy int parameter; returns old state by value
Counter operator++(int) {
Counter temp = *this;
++count;
return temp;
}
// Friend unary -- (prefix decrement)
friend Counter& operator--(Counter& c) {
--c.count;
return c;
}
int value() const { return count; }
};
int main() {
Counter c1(10), zero;
Counter c2 = ++c1; // c1 becomes 11, c2 is 11
Counter c3 = c1++; // c3 is 11, c1 becomes 12
Counter c4 = -c1; // c4 is -12, c1 remains 12
--c1; // c1 becomes 11 via friend operator--
cout << "c1=" << c1.value() << " c2=" << c2.value()
<< " c3=" << c3.value() << " c4=" << c4.value() << endl;
cout << "Is zero empty? " << (!zero ? "Yes" : "No") << endl;
return 0;
}Chapter 8: Binary Operators and String Operator Manipulation
8.1 Overloading Binary Arithmetic, Relational, and Stream Operators
A binary operator combines two operands (lhs op rhs). When overloaded as a member function, the left-hand operand invokes the function implicitly (this) and the right-hand operand is passed as the single explicit argument: lhs.operator+(rhs). Consequently, a member binary operator requires the left operand to be an object of that class—an expression such as 5.0 + complexObj fails with a member operator because 5.0 is a primitive double.
When symmetric mixed-type expressions or stream operators (cout << obj, where the left operand is ostream&) are needed, the binary operator must be overloaded as a non-member friend function taking two explicit parameters: friend Complex operator+(const Complex& a, const Complex& b);. Returning ostream& from operator<< and istream& from operator>> enables chained expressions such as cout << c1 << " and " << c2;.
| Operator Category | Member Function Signature | Friend Function Signature | Mandatory / Recommended Style |
|---|---|---|---|
Unary Prefix (++, -) |
T& operator++(); |
friend T& operator++(T& x); |
Member function preferred. |
Unary Postfix (++) |
T operator++(int); |
friend T operator++(T& x, int); |
Member function preferred. |
Binary Arithmetic (+, -, *) |
T operator+(const T& rhs) const; |
friend T operator+(const T& a, const T& b); |
Friend for symmetric mixed-type support. |
Assignment (=) & Subscript ([]) |
T& operator=(const T& rhs); |
Not permitted as friend | Must be non-static member functions. |
Stream I/O (<<, >>) |
Cannot be member of T | friend ostream& operator<<(ostream&, const T&); |
Must be non-member / friend functions. |
#include <iostream>
using namespace std;
class Complex {
private:
double real, imag;
public:
Complex(double r = 0.0, double i = 0.0) : real(r), imag(i) {}
// Binary + as friend allows both c1 + c2 and 2.5 + c1
friend Complex operator+(const Complex& a, const Complex& b) {
return Complex(a.real + b.real, a.imag + b.imag);
}
// Binary * as member function: (a+bi)(c+di) = (ac-bd) + (ad+bc)i
Complex operator*(const Complex& rhs) const {
return Complex(real * rhs.real - imag * rhs.imag,
real * rhs.imag + imag * rhs.real);
}
bool operator==(const Complex& rhs) const {
return real == rhs.real && imag == rhs.imag;
}
friend ostream& operator<<(ostream& os, const Complex& c) {
os << c.real << (c.imag >= 0 ? " + " : " - ")
<< (c.imag >= 0 ? c.imag : -c.imag) << "i";
return os;
}
friend istream& operator>>(istream& is, Complex& c) {
is >> c.real >> c.imag;
return is;
}
};
int main() {
Complex c1(3.0, 4.0), c2(1.0, -2.0);
Complex sum = c1 + c2;
Complex prod = c1 * c2;
Complex shifted = 5.0 + c1; // Works because Complex(5.0) + friend operator+
cout << "c1 = " << c1 << "\nc2 = " << c2 << endl;
cout << "Sum = " << sum << "\nProduct = " << prod << endl;
cout << "5.0 + c1 = " << shifted << endl;
return 0;
}8.2 Manipulation of Strings Using Overloaded Operators
By wrapping a dynamically allocated character buffer inside a custom MyString class, programmers can overload + for string concatenation, == and < for lexicographical comparison, = for deep-copy assignment (guarding against self-assignment if (this == &rhs) return *this;), [] for bounds-checked character indexing, and << for direct console output. The self-assignment check in operator= is critical: without it, executing s = s; would delete[] buf before copying from itself, reading freed memory.
#include <iostream>
#include <cstring>
using namespace std;
class MyString {
private:
char* buf;
int len;
public:
MyString(const char* s = "") {
len = strlen(s);
buf = new char[len + 1];
strcpy(buf, s);
}
MyString(const MyString& other) {
len = other.len;
buf = new char[len + 1];
strcpy(buf, other.buf);
}
~MyString() { delete[] buf; }
MyString& operator=(const MyString& rhs) {
if (this == &rhs) return *this; // Self-assignment guard
delete[] buf;
len = rhs.len;
buf = new char[len + 1];
strcpy(buf, rhs.buf);
return *this;
}
// Concatenation using +
MyString operator+(const MyString& rhs) const {
MyString res;
delete[] res.buf;
res.len = len + rhs.len;
res.buf = new char[res.len + 1];
strcpy(res.buf, buf);
strcat(res.buf, rhs.buf);
return res;
}
// Equality comparison using ==
bool operator==(const MyString& rhs) const {
return strcmp(buf, rhs.buf) == 0;
}
// Bounds-checked subscript operator
char& operator[](int index) {
if (index < 0 || index >= len) {
static char dummy = '\0';
return dummy;
}
return buf[index];
}
friend ostream& operator<<(ostream& os, const MyString& s) {
os << s.buf;
return os;
}
};
int main() {
MyString first("Kerala "), second("University"), check("Kerala University");
MyString combined = first + second;
combined[0] = 'k'; // Uses overloaded []
cout << "Combined: " << combined << endl;
combined[0] = 'K';
cout << "Equal? " << (combined == check ? "Yes" : "No") << endl;
return 0;
}Chapter 9: Arrays, Multi-Dimensional Arrays, and std::string
9.1 One-Dimensional and Multi-Dimensional Arrays
An array is a fixed-size, contiguous collection of homogeneous elements stored sequentially in RAM and indexed from 0 to N - 1. C++ supports arrays of primitive types as well as arrays of objects (e.g., Student batch[60];, which invokes the default constructor 60 times). A two-dimensional matrix int M[R][C] is laid out linearly in row-major order, meaning row 0 occupies the first C slots, followed immediately by row 1. The byte address of element M[i][j] is computed directly by the compiler as:
M[0][0]; i = zero-based row index; j = zero-based column index; C = total number of columns per row; S = sizeof(element_type) in bytes.When passing a 1D array to a function (void sort(int arr[], int n)), the array decays to a pointer to its first element, so the size n must be passed separately. When passing a 2D array (int mat[][MAX_C]), the column dimension must be known at compile time so the compiler can evaluate the row-major stride i * C. Matrix multiplication of an R1 × C1 matrix A with a C1 × C2 matrix B requires three nested loops and computes each entry as:
i of matrix A and column j of matrix B; C1 = shared inner dimension (columns of A = rows of B).#include <iostream>
using namespace std;
void bubbleSort(int arr[], int n) {
for (int i = 0; i < n - 1; ++i) {
bool swapped = false;
for (int j = 0; j < n - 1 - i; ++j) {
if (arr[j] > arr[j + 1]) {
int tmp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = tmp;
swapped = true;
}
}
if (!swapped) break;
}
}
int binarySearch(const int arr[], int n, int key) {
int low = 0, high = n - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (arr[mid] == key) return mid;
if (arr[mid] < key) low = mid + 1;
else high = mid - 1;
}
return -1;
}
int main() {
int data[] = {42, 17, 89, 5, 23};
int n = 5;
bubbleSort(data, n);
cout << "Index of 23: " << binarySearch(data, n, 23) << endl;
int A[2][2] = { {1, 2}, {3, 4} };
int B[2][2] = { {5, 6}, {7, 8} };
int P[2][2] = { {0, 0}, {0, 0} };
for (int i = 0; i < 2; ++i)
for (int j = 0; j < 2; ++j)
for (int k = 0; k < 2; ++k)
P[i][j] += A[i][k] * B[k][j];
cout << "Matrix Product:\n";
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 2; ++j) cout << P[i][j] << " ";
cout << endl;
}
return 0;
}9.2 C-Style Strings vs C++ std::string Class
C-style strings are null-terminated character arrays (char name[30] ending with '\0') manipulated via <cstring> functions (strlen, strcpy, strcat, strcmp). While fast, fixed-size C-strings are vulnerable to buffer overflows and manual memory errors. The C++ Standard Library <string> header provides std::string, a dynamic, bounds-safe class managing its own heap buffer automatically.
| Operation | C-Style char[] (<cstring>) |
C++ std::string (<string>) |
|---|---|---|
| Length Query | strlen(s) — scans until '\0' in linear time. |
s.length() or s.size() — constant-time stored length. |
| Assignment & Copy | strcpy(dst, src) (risks overflow if dst too small). |
dst = src; (auto-resizes safely). |
| Concatenation | strcat(dst, src) |
s1 + s2 or s1.append(s2) |
| Comparison | strcmp(s1, s2) == 0 |
s1 == s2, s1 < s2, or s1.compare(s2) |
| Substrings & Search | strstr(s, sub) returns pointer or null. |
s.substr(pos, len) and s.find(sub) (returns string::npos if absent). |
| Insert, Erase & Replace | Manual character shifting with loops. | s.insert(pos, str), s.erase(pos, len), s.replace(pos, len, str). |
| Full-Line Input | cin.getline(buf, size) |
getline(cin, str) (reads spaces safely into dynamic buffer). |
#include <iostream>
#include <string>
using namespace std;
bool isPalindrome(const string& s) {
int left = 0, right = static_cast<int>(s.length()) - 1;
while (left < right) {
if (s[left] != s[right]) return false;
++left;
--right;
}
return true;
}
int main() {
string word = "malayalam";
cout << word << " -> " << (isPalindrome(word) ? "Palindrome" : "Not Palindrome") << endl;
string course = "Object Oriented Programming";
size_t pos = course.find("Programming");
if (pos != string::npos) {
course.replace(pos, 11, "Design");
}
course.append(" using C++");
cout << "Updated: " << course << " (len=" << course.length() << ")\n";
return 0;
}9.3 Array of Objects with Overloaded Comparison and Sorting
Combining operator overloading with arrays yields expressive, reusable algorithms. When a class such as StudentScore overloads the relational operator operator> (or operator<) and the stream insertion operator operator<<, standard array sorting and printing routines operate on objects using the exact same syntax as primitive integers. Additionally, C++ allows passing arrays of objects by pointer/array decay (StudentScore list[], int n) so sorting modifies the caller's array in place without copying entire tables.
#include <iostream>
#include <string>
using namespace std;
class StudentScore {
private:
string name;
int marks;
public:
StudentScore(const string& n = "", int m = 0) : name(n), marks(m) {}
// Overload > to rank higher marks first
bool operator>(const StudentScore& rhs) const {
return marks > rhs.marks;
}
friend ostream& operator<<(ostream& os, const StudentScore& s) {
os << s.name << " (" << s.marks << ")";
return os;
}
};
void sortRankList(StudentScore arr[], int n) {
for (int i = 0; i < n - 1; ++i) {
for (int j = 0; j < n - 1 - i; ++j) {
if (arr[j + 1] > arr[j]) { // Uses overloaded operator>
StudentScore tmp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = tmp;
}
}
}
}
int main() {
StudentScore batch[4] = {
StudentScore("Lakshmi", 84),
StudentScore("Dev", 93),
StudentScore("Neha", 79),
StudentScore("Surya", 91)
};
sortRankList(batch, 4);
cout << "Merit Rank List:\n";
for (int i = 0; i < 4; ++i) {
cout << (i + 1) << ". " << batch[i] << endl;
}
return 0;
}9.4 Character Classification and C-String Manipulation Pitfalls
When working with legacy C-style character arrays (char buf[64]), programmers must always reserve one extra byte for the terminating null character ('\0'). Using bounded functions such as strncpy(dst, src, sizeof(dst) - 1) and explicitly setting dst[sizeof(dst) - 1] = '\0' prevents buffer overruns. Mixing cin >> num; followed immediately by getline(cin, line); leaves a trailing newline '\n' in the input buffer, causing getline to read an empty line; calling cin.ignore(); before getline() discards the leftover newline cleanly.
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main() {
string text = "C++ 2026 OOP Course: 5 Modules!";
int vowels = 0, digits = 0, words = 0;
bool inWord = false;
for (size_t i = 0; i < text.length(); ++i) {
char ch = text[i];
char lower = static_cast<char>(tolower(static_cast<unsigned char>(ch)));
if (lower == 'a' || lower == 'e' || lower == 'i' || lower == 'o' || lower == 'u') {
++vowels;
}
if (isdigit(static_cast<unsigned char>(ch))) {
++digits;
}
if (isspace(static_cast<unsigned char>(ch))) {
inWord = false;
} else if (!inWord) {
inWord = true;
++words;
}
}
cout << "Text: " << text << endl;
cout << "Words: " << words << " | Vowels: " << vowels
<< " | Digits: " << digits << endl;
return 0;
}Module IV: Inheritance & Runtime Polymorphism
Chapter 10: Code Reuse, Containership, and Inheritance Modes
10.1 Containership (Composition) vs Inheritance
Software engineering relies on code reuse to build complex systems from verified components. C++ provides two primary structural mechanisms for reusing existing classes:
- Containership (Composition — "Has-A" Relationship): A class embeds an object of another class as a data member. For example, a
Carhas anEngine, or anEmployeehas aDateof joining. Containership keeps the inner class's private internals hidden and exposes only the outer class's chosen interface. When the outer object is constructed, member objects are constructed first in declaration order using the outer constructor's member initializer list. - Inheritance ("Is-A" Relationship): A new derived class (child/subclass) extends an existing base class (parent/superclass), automatically inheriting its non-private data members and member functions while adding specialized attributes or overriding behaviors.
#include <iostream>
#include <string>
using namespace std;
class Date {
private:
int day, month, year;
public:
Date(int d = 1, int m = 1, int y = 2000) : day(d), month(m), year(y) {}
void show() const {
cout << day << "/" << month << "/" << year;
}
};
class Employee {
private:
int empId;
string name;
Date joinDate; // Containership: Employee "has-a" Date
public:
Employee(int id, const string& n, int d, int m, int y)
: empId(id), name(n), joinDate(d, m, y) {}
void display() const {
cout << "ID: " << empId << " | " << name << " | Joined: ";
joinDate.show();
cout << endl;
}
};
int main() {
Employee e1(501, "Nandini", 14, 8, 2024);
e1.display();
return 0;
}10.2 Defining Derived Classes and Visibility Modes
A derived class is declared using the syntax class Derived : access_specifier Base { ... };. The visibility mode (public, protected, or private—defaulting to private for class) governs how inherited public and protected members of the base class appear inside the derived class. Crucially, private members of a base class are never directly accessible to a derived class regardless of inheritance mode; they can only be accessed indirectly via inherited public or protected base methods.
| Base Class Access Level | public Inheritance |
protected Inheritance |
private Inheritance |
|---|---|---|---|
public in Base |
public in Derived (full "is-a" interface preserved) |
protected in Derived (hidden from external callers) |
private in Derived (implementation-only reuse) |
protected in Base |
protected in Derived |
protected in Derived |
private in Derived |
private in Base |
Not directly accessible | Not directly accessible | Not directly accessible |
10.3 Five Types of Inheritance in C++
C++ supports five structural inheritance topologies, each modeling distinct domain relationships:
- Single Inheritance: One derived class inherits from one base class (
A → B), such asSavingsAccountextendingAccount. - Multilevel Inheritance: A derived class acts as the base for a further derived class (
A → B → C), forming a chain of specialization such asPerson → Student → GraduateStudent. - Multiple Inheritance: A single derived class inherits simultaneously from two or more independent base classes (
class SmartPhone : public Phone, public Camera). If both bases define a member with the same name, callers disambiguate using scope resolution (obj.Phone::powerOn()). - Hierarchical Inheritance: Multiple derived classes share a single common base class (e.g.,
SavingsAccountandCurrentAccountboth inherit fromAccount). - Hybrid Inheritance: A combination of two or more patterns above—most notably combining hierarchical and multiple inheritance into a diamond-shaped hierarchy.
#include <iostream>
using namespace std;
class Academic {
protected:
int marks;
public:
Academic(int m) : marks(m) {}
void showStatus() const { cout << "Academic Marks: " << marks << endl; }
};
class Sports {
protected:
int bonus;
public:
Sports(int b) : bonus(b) {}
void showStatus() const { cout << "Sports Bonus: " << bonus << endl; }
};
// Multiple Inheritance
class Result : public Academic, public Sports {
public:
Result(int m, int b) : Academic(m), Sports(b) {}
void displayTotal() const {
// Disambiguate identically named base members with ::
Academic::showStatus();
Sports::showStatus();
cout << "Grand Total = " << (marks + bonus) << endl;
}
};
int main() {
Result r(86, 10);
r.displayTotal();
return 0;
}10.4 Constructor and Destructor Execution Order in Inheritance
When a derived object is instantiated, C++ constructs the base sub-object before the derived class body executes, ensuring inherited members are initialized before the derived constructor uses them. If the base constructor requires arguments, the derived constructor forwards them through its member initializer list: Derived(int a, int b) : Base(a), y(b) { ... }. In multiple inheritance (class D : public B1, public B2), base constructors execute strictly in the left-to-right order listed in the class header (B1, then B2, then D). Destruction proceeds in the exact reverse order: the derived destructor runs first, followed by base destructors.
Chapter 11: Virtual Functions, this Pointer, and Abstract Classes
11.1 The this Pointer and Pointers to Derived Classes
Every non-static member function receives an implicit, hidden constant pointer named this holding the memory address of the invoking object (ClassName* const this). Programmers use this to disambiguate parameter names that shadow data members (this->id = id;), to guard against self-assignment (if (this == &rhs)), and to return *this by reference for fluent method chaining (obj.setX(10).setY(20);).
C++ allows a base-class pointer (Base* ptr) to point to a derived-class object (Derived d; ptr = &d;) because every Derived object is-a Base. However, without virtual dispatch, a base pointer can invoke only the base class's version of a method (static/early binding). Note also that passing a derived object by value to a function expecting a Base parameter causes object slicing, where derived-only data members are stripped away; polymorphic code therefore always passes objects by pointer (Base*) or reference (Base&).
11.2 Function Overriding and Virtual Functions (Runtime Polymorphism)
Function overriding occurs when a derived class redefines a base-class member function with the exact same name, parameter list, and const-qualification. If the base method is non-virtual, calls through a Base* pointer resolve at compile time to Base::func(). Marking the base method with the virtual keyword enables dynamic (late) binding: the compiler builds a per-class virtual table (vtable) of function pointers and embeds a hidden vptr inside each polymorphic object. At runtime, ptr->draw() follows vptr → vtable to invoke the true dynamic object's overridden method. Modern C++ adds the override specifier on derived methods so the compiler catches signature mismatches at compile time.
| Feature | Function Overloading (Compile-Time) | Function Overriding (Runtime) |
|---|---|---|
| Scope | Same class or namespace scope. | Across Base and Derived classes. |
| Signature | Must differ in parameter count, types, or order. | Must match identically in name, parameters, and const. |
| Binding Mechanism | Static / early binding at compile time. | Dynamic / late binding via virtual and vtable. |
| Return Type | May differ if parameter list differs. | Must match (or be covariant pointer/reference). |
11.3 Virtual Base Classes and Abstract Classes
In diamond hybrid inheritance (A → B, A → C, and B, C → D), class D normally inherits two separate copies of A's members—one via B and one via C—causing compile-time ambiguity when accessing A's members on a D object. Declaring the intermediate inheritances as virtual base classes (class B : virtual public A and class C : virtual public A) instructs the compiler to merge both paths into a single shared A sub-object inside D. In virtual inheritance, the most-derived class (D) is directly responsible for invoking the virtual base class constructor A().
An abstract class is a base class designed solely as an interface blueprint that cannot be instantiated directly. A class becomes abstract when it contains at least one pure virtual function declared with = 0 (e.g., virtual double area() const = 0;). Any concrete derived class must override all pure virtual functions; otherwise, it too remains abstract. Abstract base classes should also declare a virtual ~Base() {} destructor so deleting a derived object through a Base* pointer invokes the derived destructor properly before freeing base resources.
#include <iostream>
#include <string>
using namespace std;
// Abstract base class
class Shape {
protected:
string label;
public:
Shape(const string& label) {
this->label = label; // this pointer disambiguates shadowed name
}
virtual double area() const = 0; // Pure virtual function
virtual void show() const {
cout << label << " -> Area: " << area() << endl;
}
virtual ~Shape() {} // Virtual destructor for safe polymorphic delete
};
class Rectangle : public Shape {
double w, h;
public:
Rectangle(double w, double h) : Shape("Rectangle"), w(w), h(h) {}
double area() const override { return w * h; }
};
class Circle : public Shape {
double r;
public:
Circle(double r) : Shape("Circle"), r(r) {}
double area() const override { return 3.14159 * r * r; }
};
// Virtual base class resolving diamond ambiguity
class Person {
public:
int id;
Person(int i = 101) : id(i) {}
};
class Student : virtual public Person {};
class Employee : virtual public Person {};
class WorkingStudent : public Student, public Employee {
public:
WorkingStudent(int i) : Person(i) {} // Most-derived initializes virtual base
};
int main() {
Shape* shapes[2];
shapes[0] = new Rectangle(4.0, 5.0);
shapes[1] = new Circle(3.0);
for (int i = 0; i < 2; ++i) {
shapes[i]->show(); // Runtime polymorphic dispatch via vtable
delete shapes[i]; // Calls derived destructor then Shape destructor
}
WorkingStudent ws(999);
cout << "Shared Person ID (no diamond ambiguity): " << ws.id << endl;
return 0;
}#include <iostream>
using namespace std;
class BoxBuilder {
private:
int length, width, height;
public:
BoxBuilder() : length(1), width(1), height(1) {}
BoxBuilder& setLength(int l) { this->length = l; return *this; }
BoxBuilder& setWidth(int w) { this->width = w; return *this; }
BoxBuilder& setHeight(int h) { this->height = h; return *this; }
int volume() const { return length * width * height; }
};
int main() {
BoxBuilder box;
int vol = box.setLength(10).setWidth(5).setHeight(4).volume();
cout << "Chained Box Volume = " << vol << endl;
return 0;
}Chapter 12: Polymorphic Design Patterns and Memory Layout
12.1 Virtual Table (vtable) and Object Slicing Mechanics
Understanding how C++ implements runtime polymorphism clarifies both its power and its constraints. Every class declaring or inheriting at least one virtual function receives a compiler-generated static lookup table called a vtable containing function pointers to the most-derived overrides for that class. Each object instance of that class carries a hidden pointer—the vptr—initialized by the constructor to point to its class's vtable. When a call basePtr->computePay() executes, the CPU dereferences basePtr->vptr, looks up the slot for computePay, and jumps to the target function in constant O(1) time.
This mechanism explains why object slicing occurs when a derived object is passed or assigned by value to a base variable (Base b = derivedObj;): the copy operation allocates only enough stack space for a Base object, discards all derived data members, and resets b's vptr to Base's vtable. To preserve polymorphic identity, always store and pass polymorphic hierarchies via base pointers (Base*) or base references (Base&).
12.2 Applied Payroll System Using Hierarchical Inheritance and Interfaces
To consolidate single, hierarchical, and abstract-class polymorphism, Listing 4.5 models an enterprise payroll engine. An abstract base class Staff defines common identity attributes and a pure virtual calculateSalary() contract, while SalariedStaff and HourlyStaff provide distinct concrete implementations dispatched uniformly through a Staff* array.
#include <iostream>
#include <string>
using namespace std;
class Staff {
protected:
int id;
string name;
public:
Staff(int id, const string& name) : id(id), name(name) {}
virtual double calculateSalary() const = 0; // Pure virtual interface
virtual void printSlip() const {
cout << "ID #" << id << " | " << name
<< " | Net Pay: Rs. " << calculateSalary() << endl;
}
virtual ~Staff() {}
};
class SalariedStaff : public Staff {
private:
double monthlyBasic;
double allowance;
public:
SalariedStaff(int id, const string& n, double basic, double allow)
: Staff(id, n), monthlyBasic(basic), allowance(allow) {}
double calculateSalary() const override {
return monthlyBasic + allowance;
}
};
class HourlyStaff : public Staff {
private:
double hourlyRate;
int hoursWorked;
public:
HourlyStaff(int id, const string& n, double rate, int hrs)
: Staff(id, n), hourlyRate(rate), hoursWorked(hrs) {}
double calculateSalary() const override {
return hourlyRate * hoursWorked;
}
};
int main() {
Staff* payroll[3];
payroll[0] = new SalariedStaff(101, "Anitha", 42000.0, 8000.0);
payroll[1] = new HourlyStaff(102, "Vikram", 450.0, 60);
payroll[2] = new SalariedStaff(103, "Priya", 50000.0, 10000.0);
double totalOutlay = 0.0;
for (int i = 0; i < 3; ++i) {
payroll[i]->printSlip();
totalOutlay += payroll[i]->calculateSalary();
delete payroll[i];
}
cout << "Total Monthly Payroll: Rs. " << totalOutlay << endl;
return 0;
}| Inheritance Concept | Keyword / Syntax | Primary Architectural Purpose |
|---|---|---|
| Containership | Member object inside class | Models "has-a" composition without exposing inner private state. |
| Virtual Function | virtual ret func(); |
Enables dynamic late binding via vtable/vptr at runtime. |
| Pure Virtual Function | virtual ret func() = 0; |
Makes base class abstract and forces derived classes to implement contract. |
| Virtual Base Class | class B : virtual public A |
Eliminates duplicate base sub-objects in diamond hybrid inheritance. |
| Virtual Destructor | virtual ~Base() {} |
Ensures derived destructor executes when deleting via Base*. |
this Pointer |
this->member / return *this; |
References invoking object for disambiguation and method chaining. |
12.3 Constructor & Destructor Tracing in Multi-Level and Hierarchical Trees
Tracing constructor and destructor invocation order in deep inheritance trees is a frequent examination and debugging requirement. Consider a three-level hierarchy Device → Computer → Laptop where Laptop also contains a member object Battery (containership). When a Laptop is instantiated, C++ executes constructors in strict dependency order: (1) Base class Device(), (2) Intermediate base Computer(), (3) Contained member object Battery() in declaration order, and (4) Derived body Laptop(). When the Laptop leaves scope, destructors run in the exact mirror-image reverse sequence: ~Laptop(), ~Battery(), ~Computer(), and finally ~Device().
#include <iostream>
using namespace std;
class Device {
public:
Device() { cout << "1. Device constructed\n"; }
~Device() { cout << "4. Device destroyed\n"; }
};
class Computer : public Device {
public:
Computer() { cout << "2. Computer constructed\n"; }
~Computer() { cout << "3. Computer destroyed\n"; }
};
class Battery {
public:
Battery() { cout << "3. Battery member constructed\n"; }
~Battery() { cout << "2. Battery member destroyed\n"; }
};
class Laptop : public Computer {
private:
Battery cell; // Contained member object
public:
Laptop() { cout << "4. Laptop constructed\n"; }
~Laptop() { cout << "1. Laptop destroyed\n"; }
};
int main() {
cout << "--- Creating Laptop ---\n";
Laptop myLaptop;
cout << "--- Leaving main() scope ---\n";
return 0;
}12.4 Pointers to Derived Classes vs Base Pointers
A pointer of type Derived* can access all public members of both Base and Derived directly. Conversely, a pointer of type Base* pointing to a Derived object can invoke only the interface declared in Base (even if the Derived class defines additional non-virtual helper methods). To safely downcast a Base* back to a Derived* when the base class is polymorphic (has at least one virtual function), C++ provides dynamic_cast<Derived*>(basePtr), which verifies the runtime type via RTTI (Run-Time Type Information) and returns nullptr if the cast is invalid.
#include <iostream>
using namespace std;
class Media {
public:
virtual void play() const { cout << "Playing generic media\n"; }
virtual ~Media() {}
};
class Video : public Media {
public:
void play() const override { cout << "Playing HD video stream\n"; }
void enableSubtitles() const { cout << "Subtitles enabled\n"; }
};
int main() {
Media* item = new Video();
item->play(); // Polymorphic call -> Video::play()
// Safe runtime-checked downcast
if (Video* vid = dynamic_cast<Video*>(item)) {
vid->enableSubtitles();
}
delete item;
return 0;
}12.5 Access Control Summary, final Specifier, and Common Inheritance Pitfalls
Modern C++ provides the final specifier for two defensive design guarantees: marking a virtual method final prevents any further derived class from overriding it, while marking an entire class class SecureToken final { ... }; prohibits any class from inheriting from it. Programmers should also guard against three frequent inheritance pitfalls:
- Name Hiding Across Scopes: Defining a non-virtual function
show(int x)in a derived class hides all overloadedshow()variants in the base class unless explicitly brought into scope viausing Base::show;. - Forgetting Virtual Destructors: Deleting a derived object via a
Base*pointer when~Base()is non-virtual leaves derived resources unfreed. - Calling Virtual Functions Inside Constructors/Destructors: Inside a base constructor or destructor, the derived part of the object has not yet been constructed (or has already been destroyed), so virtual dispatch resolves strictly to the base class version rather than the derived override.
#include <iostream>
using namespace std;
class Logger {
public:
void log(const char* msg) const { cout << "[LOG] " << msg << endl; }
void log(int code) const { cout << "[CODE] " << code << endl; }
};
class FileLogger : public Logger {
public:
using Logger::log; // Prevents name hiding of Logger::log(int)
void log(const char* msg) const {
cout << "[FILE-LOG] " << msg << endl;
}
};
int main() {
FileLogger fl;
fl.log("System initialized"); // Calls FileLogger::log(const char*)
fl.log(200); // Calls Logger::log(int) via using declaration
return 0;
}In summary, inheritance and runtime polymorphism work together to support the Open–Closed Principle: software modules should be open for extension (by deriving new subclasses such as CommissionStaff or AudioMedia) yet closed for modification (existing polymorphic loops using Staff* or Media* require zero edits when new subclasses are introduced).
Module V: File I/O and Exception Handling
Chapter 12: C++ Exception Handling
12.1 Synchronous Error Handling with try, throw, and catch
Traditional C error handling relies on returning magic sentinel codes (such as -1 or NULL) or inspecting global errno. Callers can easily ignore return codes, and constructors—which have no return type—cannot return error flags at all. C++ Exception Handling separates normal algorithmic logic from error-recovery logic using three keywords:
tryBlock: Encloses code statements that might encounter an exceptional runtime condition (such as division by zero, out-of-range array access, or file open failure).throwStatement: Signals that an anomaly occurred by constructing and throwing an exception object (primitive, string, or custom exception class instance) out of the normal execution path.catchBlock: Immediately follows atryblock and specifies the parameter type it handles. When an exception is thrown, the C++ runtime searches backward up the call stack for a matching handler.
During this search, C++ performs stack unwinding: every local automatic object constructed inside the active try block and intermediate function frames is automatically destroyed (its destructor is invoked in reverse LIFO order) before control enters the matching catch block. This deterministic cleanup underpins the RAII (Resource Acquisition Is Initialization) idiom, ensuring heap allocations, locks, and file handles never leak when exceptions occur. If no matching catch block exists anywhere up to main(), the runtime invokes std::terminate() and aborts the program.
12.2 Multiple Catch Blocks, Catch-All, Rethrowing, and Standard Exceptions
A single try block may be followed by multiple catch blocks ordered from most specific (derived) type to most general (base) type; placing a base-class handler before a derived handler would intercept derived exceptions prematurely. Catching exceptions by const reference (catch (const exception& e)) avoids unnecessary copying and prevents object slicing. A catch-all handler written as catch (...) matches any thrown exception type and must always appear last as a safety net.
Inside a catch handler, an exception may be logged or partially handled and then forwarded to an outer caller using a bare throw; statement (rethrowing the original exception object intact). Standard C++ also defines a hierarchy of exception classes in <stdexcept> rooted at std::exception, each exposing a descriptive what() method:
| Standard Exception Class | Header | Typical Failure Condition |
|---|---|---|
std::exception |
<exception> |
Root base class providing virtual const char* what() const. |
std::bad_alloc |
<new> |
Thrown by new when heap memory allocation fails. |
std::invalid_argument |
<stdexcept> |
Subclass of logic_error for illegal function arguments. |
std::out_of_range |
<stdexcept> |
Subclass of logic_error for bounds violations (e.g., string::at()). |
std::runtime_error |
<stdexcept> |
Base class for external or runtime failures (e.g., overflow, I/O errors). |
#include <iostream>
#include <stdexcept>
#include <string>
using namespace std;
class ResourceGuard {
string name;
public:
ResourceGuard(const string& n) : name(n) {
cout << "[Acquire] " << name << endl;
}
~ResourceGuard() {
cout << "[Release via Stack Unwind] " << name << endl;
}
};
class InsufficientFunds : public runtime_error {
public:
InsufficientFunds(const string& msg) : runtime_error(msg) {}
};
double divideSafe(double num, double den) {
if (den == 0.0) {
throw invalid_argument("Denominator cannot be zero.");
}
return num / den;
}
void processWithdrawal(double balance, double amount) {
ResourceGuard ledgerLock("LedgerLock");
try {
if (amount <= 0) throw 400; // Integer error code
if (amount > balance) throw InsufficientFunds("Balance too low.");
cout << "Withdrawn Rs. " << amount << endl;
} catch (const InsufficientFunds& e) {
cout << "Audit Log: " << e.what() << endl;
throw; // Rethrow to outer caller; ledgerLock still unwinds cleanly
}
}
int main() {
try {
cout << "10 / 2 = " << divideSafe(10.0, 2.0) << endl;
processWithdrawal(1000.0, 2500.0);
} catch (const invalid_argument& e) {
cout << "Math Error: " << e.what() << endl;
} catch (const InsufficientFunds& e) {
cout << "Transaction Declined: " << e.what() << endl;
} catch (int code) {
cout << "Error Code: " << code << endl;
} catch (...) {
cout << "Unknown exception caught." << endl;
}
return 0;
}Chapter 13: File Streams, Modes, and File Pointer Manipulation
13.1 File Stream Classes and Opening / Closing Files
Console I/O is volatile: data vanishes once the program exits. Persistent storage on disk is managed in C++ through the <fstream> header, which derives three specialized file stream classes from istream and ostream (both inheriting stream formatting and state flags from ios):
ofstream(Output File Stream): Inherits fromostream; used to create and write data to files.ifstream(Input File Stream): Inherits fromistream; used to open and read data from existing files.fstream(Bidirectional File Stream): Inherits fromiostream; supports simultaneous reading and writing on the same file.
A file can be opened either by passing the filename to the stream's constructor (ofstream out("data.txt");) or by calling the open() member function explicitly on an existing stream object (out.open("data.txt", ios::out);). Always verify success using if (!out.is_open()) or if (!out) before reading or writing. Calling close() flushes any buffered bytes to disk and releases the operating system file descriptor so the same stream object can be reused to open another file (the destructor also closes automatically if still open).
13.2 File Open Modes and Stream State Flags
File modes defined in class ios control how a file is opened and may be combined using the bitwise OR operator (|):
| File Mode Flag | Semantic Behavior | Default Stream Association |
|---|---|---|
ios::in |
Opens file for reading; fails if file does not exist (unless combined with ios::out). |
Default for ifstream. |
ios::out |
Opens file for writing; creates file if absent, truncates existing content unless combined with ios::app or ios::in. |
Default for ofstream. |
ios::app |
Append mode: all writes go strictly to the end of the file, preserving prior content. | Optional with ofstream / fstream. |
ios::ate |
"At End": opens positioned at end, but allows seeking anywhere afterward. | Optional. |
ios::trunc |
Discards existing file contents upon opening (length becomes 0). | Implicit with ios::out alone. |
ios::binary |
Transfers raw bytes without newline (\n ↔ \r\n) text translation. |
Mandatory for binary object records. |
Every stream maintains four internal state bits queried via member functions: good() (returns true when no error bits are set), eof() (returns true after attempting to read past end-of-file), fail() (returns true on format mismatch or open failure), and bad() (returns true on unrecoverable hardware/stream corruption). Calling stream.clear() resets error flags so the stream can continue operating after an EOF or failed seek.
13.3 Manipulation of File Pointers and I/O Operations
Every open file stream maintains internal cursor positions: a get pointer (for reading) and a put pointer (for writing). C++ supports both sequential and random-access I/O through four pointer manipulation methods and three anchor constants (ios::beg start of file, ios::cur current position, ios::end end of file):
seekg(offset, origin)/seekp(offset, origin): Moves the get (read) or put (write) pointer byoffsetbytes relative toorigin. For fixed-size binary records of sizeSbytes, jumping directly to record indexr(0-based) uses:Where: r = zero-based record index (0, 1, 2, ...); sizeof(Record) = fixed byte size of one binary struct/class record.tellg()/tellp(): Returns the current byte offset (asstreampos) of the get or put pointer. Callingseekg(0, ios::end)followed bytellg()computes total file size in bytes.- Character & Line I/O:
get(ch)andput(ch)read/write single characters (preserving spaces and newlines);getline(fin, str)reads a full text line safely into astd::string. - Binary Block I/O:
read(reinterpret_cast<char*>(&obj), sizeof(obj))andwrite(reinterpret_cast<const char*>(&obj), sizeof(obj))transfer raw object bytes directly inios::binarymode. Note that classes containing raw pointers (orstd::string) should not be written verbatim withwrite()because saving a RAM pointer address produces invalid addresses when reloaded; fixed-sizechar[]arrays and primitive fields are used in binary records.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ofstream fout("notes.txt");
if (!fout.is_open()) {
cerr << "Failed to create notes.txt\n";
return 1;
}
fout << "Object Oriented Programming in C++\n";
fout << "Exception Handling and File Streams\n";
fout.close();
ifstream fin("notes.txt");
if (!fin) return 1;
string line;
int lineCount = 0;
while (getline(fin, line)) {
++lineCount;
cout << lineCount << ": " << line << endl;
}
fin.clear(); // Clear EOF flag before seeking
fin.seekg(0, ios::beg); // Rewind to start for char count
char ch;
int charCount = 0;
while (fin.get(ch)) {
++charCount;
}
cout << "Lines: " << lineCount << ", Characters: " << charCount << endl;
fin.close();
return 0;
}#include <iostream>
#include <fstream>
using namespace std;
struct StudentRecord {
int rollNo;
char name[32];
double gpa;
};
int main() {
StudentRecord batch[3] = {
{101, "Aarav", 8.7},
{102, "Diya", 9.2},
{103, "Kabir", 8.4}
};
// 1. Write initial binary records
ofstream fout("students.dat", ios::binary | ios::trunc);
if (!fout.is_open()) return 1;
fout.write(reinterpret_cast<const char*>(batch), sizeof(batch));
fout.close();
// 2. Open bidirectionally to read and update 2nd record (index 1) in-place
fstream fio("students.dat", ios::in | ios::out | ios::binary);
if (!fio) return 1;
fio.seekg(0, ios::end);
streampos totalBytes = fio.tellg();
cout << "Total records stored: " << (totalBytes / sizeof(StudentRecord)) << endl;
StudentRecord rec;
streamoff targetOffset = static_cast<streamoff>(1 * sizeof(StudentRecord));
fio.seekg(targetOffset, ios::beg);
fio.read(reinterpret_cast<char*>(&rec), sizeof(StudentRecord));
cout << "Before Update -> Roll: " << rec.rollNo
<< ", Name: " << rec.name << ", GPA: " << rec.gpa << endl;
rec.gpa = 9.6; // Update GPA and write back to exact same byte offset
fio.seekp(targetOffset, ios::beg);
fio.write(reinterpret_cast<const char*>(&rec), sizeof(StudentRecord));
// Verify update
fio.seekg(targetOffset, ios::beg);
fio.read(reinterpret_cast<char*>(&rec), sizeof(StudentRecord));
cout << "After Update -> Roll: " << rec.rollNo
<< ", Name: " << rec.name << ", GPA: " << rec.gpa << endl;
fio.close();
return 0;
}Chapter 14: Integrated File Persistence and Exception Safety
14.1 Combining File Streams with Exception Handling
In production C++ applications, file I/O and exception handling work hand in hand. Disk operations are inherently prone to external failures—missing files, permission denials, full disks, or corrupted record counts. Rather than scattering if (!fin) checks across every caller, a well-designed file repository function opens streams inside a try block, throws descriptive std::runtime_error objects on failure, and relies on stack unwinding to close local ifstream/ofstream objects automatically via their destructors (RAII) even when an exception interrupts processing mid-file.
Streams can also be configured to throw std::ios_base::failure automatically on error bits using stream.exceptions(ifstream::failbit | ifstream::badbit);, though manual validation after open() and after read/write operations remains the clearest approach when eof() is expected at the end of a read loop.
| Stream State / Pointer Method | Return Type / Parameters | Operational Meaning |
|---|---|---|
is_open() |
bool |
Returns true if stream is currently bound to an open OS file. |
eof() |
bool |
Returns true after a read operation hits end-of-file. |
fail() / bad() |
bool |
fail() detects format/open error; bad() detects hardware/stream failure. |
clear() |
void |
Resets all stream error state bits back to goodbit. |
seekg(off, dir) |
istream& |
Repositions input (get) pointer relative to ios::beg, ios::cur, or ios::end. |
seekp(off, dir) |
ostream& |
Repositions output (put) pointer relative to anchor direction. |
tellg() / tellp() |
streampos |
Returns current byte offset of the get or put pointer from file start. |
#include <iostream>
#include <fstream>
#include <stdexcept>
#include <string>
using namespace std;
void copyTextFile(const string& srcPath, const string& dstPath) {
ifstream fin(srcPath);
if (!fin.is_open()) {
throw runtime_error("Cannot open source file: " + srcPath);
}
ofstream fout(dstPath, ios::trunc);
if (!fout.is_open()) {
throw runtime_error("Cannot create destination file: " + dstPath);
}
char ch;
long bytesCopied = 0;
while (fin.get(ch)) {
fout.put(ch);
if (fout.fail()) {
throw runtime_error("Write failure while writing to " + dstPath);
}
++bytesCopied;
}
cout << "Successfully copied " << bytesCopied << " bytes.\n";
// fin and fout destructors automatically close both files on exit or throw
}
int main() {
try {
copyTextFile("notes.txt", "notes_backup.txt");
copyTextFile("missing_file.txt", "out.txt"); // Triggers exception
} catch (const runtime_error& e) {
cerr << "File I/O Exception: " << e.what() << endl;
}
return 0;
}14.2 Exception Propagation Across Call Chains and noexcept
When a deeply nested helper function throws an exception without a local try-catch block, the exception propagates upward through intermediate callers until a matching catch handler is located. This propagation allows low-level validation routines (such as matrix bounds checks or parser routines) to focus strictly on detecting errors while high-level controller functions decide whether to retry, prompt the user, or log to disk. Functions guaranteed never to emit exceptions (such as destructors and move operations) can be marked with the noexcept specifier (void swap(int& a, int& b) noexcept), enabling compiler optimizations and signaling safety contracts to callers.
14.3 Applied Student Record Manager Using Binary Files and Exceptions
Listing 5.5 integrates Module V's file streams, binary modes, file pointers, and exception handling into a complete record persistence manager. It validates file opening, writes structured records in binary mode, searches for a target roll number sequentially, and throws a custom RecordNotFoundException if the requested student does not exist.
#include <iostream>
#include <fstream>
#include <stdexcept>
#include <cstring>
using namespace std;
class RecordNotFoundException : public runtime_error {
public:
RecordNotFoundException(const string& msg) : runtime_error(msg) {}
};
struct ExamRecord {
int roll;
char subject[24];
int score;
};
void saveRecords(const char* filename, const ExamRecord arr[], int count) {
ofstream fout(filename, ios::binary | ios::trunc);
if (!fout.is_open()) {
throw runtime_error("Unable to open file for writing.");
}
fout.write(reinterpret_cast<const char*>(arr), count * sizeof(ExamRecord));
fout.close();
}
ExamRecord findByRoll(const char* filename, int targetRoll) {
ifstream fin(filename, ios::binary);
if (!fin.is_open()) {
throw runtime_error("Unable to open database file.");
}
ExamRecord rec;
while (fin.read(reinterpret_cast<char*>(&rec), sizeof(ExamRecord))) {
if (rec.roll == targetRoll) {
fin.close();
return rec;
}
}
fin.close();
throw RecordNotFoundException("Roll number not found in binary file.");
}
int main() {
ExamRecord list[3] = {
{201, "C++ OOP", 91},
{202, "Data Structures", 85},
{203, "DBMS", 88}
};
try {
saveRecords("exams.bin", list, 3);
ExamRecord found = findByRoll("exams.bin", 202);
cout << "Found -> Roll: " << found.roll
<< ", Subject: " << found.subject
<< ", Score: " << found.score << endl;
findByRoll("exams.bin", 999); // Triggers RecordNotFoundException
} catch (const RecordNotFoundException& e) {
cerr << "Search Error: " << e.what() << endl;
} catch (const exception& e) {
cerr << "System Error: " << e.what() << endl;
}
return 0;
}14.4 Text vs Binary File Storage and Stream Formatting
Choosing between text files and binary files involves a trade-off between human readability and storage/speed efficiency. Text files encode numbers as ASCII character sequences (for example, the 4-byte integer 1000000 consumes 7 bytes in ASCII), making them easy to inspect in any text editor and portable across different CPU endianness architectures. Binary files store raw in-memory bit representations directly via write() and read(), preserving exact floating-point precision without decimal rounding and enabling constant-time O(1) random-access jumps via seekg() and seekp() because every record occupies an identical fixed byte stride.
When writing formatted text tables to an ofstream, all stream manipulators from <iomanip>—such as setw(), setprecision(), fixed, left, and right—work identically on file streams as on cout because ofstream inherits directly from ostream.
#include <iostream>
#include <fstream>
#include <iomanip>
#include <sstream>
#include <string>
using namespace std;
int main() {
// Write formatted CSV file
ofstream csvOut("grades.csv", ios::trunc);
if (!csvOut.is_open()) return 1;
csvOut << "Roll,Name,Marks\n";
csvOut << "101,Meera,92\n";
csvOut << "102,Arjun,87\n";
csvOut.close();
// Parse CSV file line-by-line
ifstream csvIn("grades.csv");
if (!csvIn.is_open()) return 1;
string header, line;
getline(csvIn, header); // Skip header row
cout << left << setw(8) << "Roll" << setw(15) << "Name" << "Marks\n";
while (getline(csvIn, line)) {
stringstream ss(line);
string roll, name, marks;
getline(ss, roll, ',');
getline(ss, name, ',');
getline(ss, marks, ',');
cout << left << setw(8) << roll << setw(15) << name << marks << endl;
}
csvIn.close();
return 0;
}14.5 Best Practices for Robust File Handling and Exception Safety
When building persistent C++ applications, follow five defensive engineering practices:
- Immediate Stream Validation: Always verify
is_open()immediately after constructing or opening any file stream before attempting I/O. - Correct Loop Termination: Prefer
while (getline(fin, line))orwhile (fin.read(...))rather thanwhile (!fin.eof()), becauseeof()only becomestrueafter a failed read attempt (which otherwise processes the last record twice). - Binary Serialization Discipline: Never write classes containing raw pointers or
std::stringdirectly withwrite(); serialize fixed-sizechar[]buffers or write explicit length-prefixed strings. - Ordered Exception Catching: Catch exceptions by
constreference ordered from most-derived subclass to basestd::exception, placingcatch (...)last. - RAII Resource Cleanup: Rely on local stream destructors so files close automatically even when exceptions unwind the stack.
| Anchor Constant | Reference Position | Typical Offset Sign & Usage |
|---|---|---|
ios::beg |
Beginning of file (byte 0) | Non-negative offset; jumps directly to record r * sizeof(Record). |
ios::cur |
Current get/put cursor position | Positive (forward) or negative (backward) relative skip. |
ios::end |
End of file | Zero offset measures file size via tellg(); negative offset reads tail records. |
University of Kerala FYUGP Academic Framework
Syllabus details for BCA Semester 2 under official University of Kerala regulations.
Assessment comprises a 70-mark End-Semester Examination (2.5 Hours) and 30-mark Continuous Internal Evaluation.
About Object Oriented Programming using C++ (University of Kerala BCA Sem 2)
Object Oriented Programming using C++ (UK2DSCCAP100 • 4 Credits • 60 Hours (4 Hrs/Week)) is a DSC offering under the Bachelor of Computer Applications (BCA) Four-Year Undergraduate Programme (UoK FYUGP Regulations 2024 / 2025) at the University of Kerala. Structured across five sequentially integrated instructional modules, the course builds solid theoretical foundations and hands-on technical proficiency in object oriented programming using c++. Students engage with core computing principles, structured problem-solving, implementation techniques, and modern industry practices aligned with Kerala State Higher Education Council outcome-based education standards.
Object Oriented Programming using C++ Module-by-Module Curriculum Breakdown
Official syllabus unit modules prescribed by the University of Kerala FYUGP framework:
Introduction to C++
Early software systems were built primarily using Procedure-Oriented Programming (POP) in languages such as C, Pascal, and FORTRAN. In POP, a problem is decomposed into a sequence of functions (procedures) that operate on shared global or local data structures. While effective for small-scale utilities, procedural architectures exhibit severe structural fragility as codebases grow beyond tens of thousands of lines. Because global data is freely accessible to any function, an unintended modification in one module can silently corrupt state relied upon by dozens of other routines.
Classes and Objects
In C++, a class is a user-defined composite type declared with the class keyword, terminated by a mandatory semicolon };. A class groups data members (variables representing state) and member functions (methods operating on that state) under explicit access specifiers: Member functions may be defined inside the class body (implicitly treated as inline requests) or declared inside the class and defined outside using the scope resolution operator ( ClassName::funcName ).
Operator Overloading, Arrays & Strings
Built-in operators such as +, -, *, and == work natively on primitive types like int and double, yet fail on user-defined class types unless explicitly taught how to behave. Operator overloading is a form of compile-time polymorphism that assigns additional, domain-appropriate semantics to existing C++ operators when applied to class objects. For instance, adding two Complex numbers via c3 = c1 + c2 or comparing two String objects via s1 == s2 reads far more naturally than c3 = c1.
Inheritance & Runtime Polymorphism
Software engineering relies on code reuse to build complex systems from verified components.
File I/O and Exception Handling
Traditional C error handling relies on returning magic sentinel codes (such as -1 or NULL ) or inspecting global errno. Callers can easily ignore return codes, and constructors—which have no return type—cannot return error flags at all. C++ Exception Handling separates normal algorithmic logic from error-recovery logic using three keywords: During this search, C++ performs stack unwinding: every local automatic object constructed inside the active try block and intermediate function frames is automatically destroyed (its destructor is invoked in reverse LIFO order) before control enters the matching catch block.
Core Curriculum & Key Topics
- Foundations of Object-Oriented Programming
- 1 Evolution from Procedural to Object-Oriented Paradigms
- 2 Characteristics and Applications of OOP
- 3 Core OOP Concepts
- Basic C++ Program Structure, Data Types, and Streams
- 1 Anatomy of a C++ Program and Compilation Pipeline
- 2 Keywords, Identifiers, Variables, References, and Constants
- 3 Basic Data Types and Memory Representation
Learning Outcomes
- Demonstrate authoritative comprehension of the foundational concepts, architectures, and principles of object oriented programming using c++.
- Apply algorithmic, programming, or analytical techniques to design and evaluate practical computing solutions.
- Analyze system trade-offs, security considerations, and industry standards relevant to modern software and IT environments.
- Implement, test, and document structured technical workflows aligned with professional computing practices.
- Achieve exam-ready mastery of University of Kerala FYUGP BCA question patterns across short concepts, technical comparisons, and comprehensive essays.
University of Kerala Examination Scheme for Object Oriented Programming using C++
The evaluation framework for Object Oriented Programming using C++ (UK2DSCCAP100) under University of Kerala FYUGP regulations combines Continuous Internal Evaluation (30 Marks) with the university End-Semester Examination (70 Marks) for a total of 100 Marks (2.5 Hours duration):
10 Questions × 3 Marks (Maximum ceiling 24 Marks). Short definitional and conceptual questions covering all 5 syllabus modules.
8 Questions × 6 Marks (Maximum ceiling 36 Marks). Paragraph questions, comparative evaluations, and analytical problems.
2 Questions × 10 Marks (Answer any 1 for 10 Marks). Long-form essay or comprehensive numerical workout problem.
Exam Preparation Strategy:
To score top marks in the University of Kerala UK2DSCCAP100 (Object Oriented Programming using C++) examination: 1. Write Clean, Traceable Code Snippets: Always include well-indented syntax examples with sample input and expected output for programming questions. 2. Explain Logic & Control Flow Step-by-Step: Before writing full programs, briefly outline the algorithm, key functions, or class hierarchy so examiners can award full step marks. 3. Highlight Edge Cases & Syntax Rules: Mention common runtime pitfalls, data type constraints, or security/validation practices where relevant. 4. Manage Time Across Sections: For the 2.5-hour 70-mark external paper, allocate 25 minutes to Part A definitions, 50 minutes to Part B short programs and comparisons, and 75 minutes to Part C full code-backed essays.
Exam Preparation & Study Guides — Object Oriented Programming using C++
What is Introduction to OOP, Characteristics, and Applications and why is it important in Object Oriented Programming using C++?
Object-Oriented Programming (OOP) shifts software design from procedure-centric top-down routines acting on exposed global data to self-contained software objects that bundle state and behavior together, improving modularity, maintainability, and defect isolation across large codebases.
What is Decision and Control Structures and why is it important in Object Oriented Programming using C++?
Conditional branching directs execution flow using Boolean predicates evaluated at runtime.
What is Name Mangling & Resolution and why is it important in Object Oriented Programming using C++?
The compiler encodes parameter types into unique linker symbols and selects overloads by exact match, integral promotion, standard conversion, or user conversion.
What is the key distinction in Mandatory Member vs Mandatory Friend Operators?
Assignment (=), subscript ([]), function call (()), and arrow (->) must be non-static member functions; stream insertion (<<) and extraction (>>) must be non-member/friend functions returning ostream&/istream& for chaining.
What is Accessing Base Members, Constructor Order, and Name Hiding and why is it important in Object Oriented Programming using C++?
Derived classes initialize base sub-objects before executing their own constructor bodies and tear down in exact reverse order.
What is the official course code and credit structure for Object Oriented Programming using C++ at University of Kerala?
Object Oriented Programming using C++ carries the official course code UK2DSCCAP100 under the University of Kerala FYUGP BCA framework. It is awarded 4 credits (60 Hours (4 Hrs/Week)), evaluated through 30 marks Continuous Internal Evaluation (CIE) and 70 marks End-Semester Examination (ESE).
Where can students download free PDF notes for Object Oriented Programming using C++?
Students can read all 5 module notes online and download verified chapter-wise PDFs, combined exam notes, and quick revision sheets for Object Oriented Programming using C++ (UK2DSCCAP100) directly from DegreeLive (degreelive.in) with zero paywalls or sign-ups.
Course outlines and study notes follow official University of Kerala curricula. Curated by Anoop (Thiruvananthapuram).
For feedback or corrections, contact [email protected].
Related Study Resources & Student Support
Related Semester 2 Subjects
Browse study notes for other courses in BCA Sem 2:
Financial Aid & Grants 2026-27
Check eligibility criteria and deadlines for Kerala government and merit scholarships (e-Grantz 3.0, KSHEC, DCE).
Request Notes
Can't find what you're looking for? Let us know which subject notes you need.