UNIT 2: OBJECT-ORIENTED PROGRAMMING & METHODOLOGY (C++ FOCUS) - SHORT NOTES
I. FUNDAMENTALS OF OBJECT-ORIENTED PROGRAMMING (OOP)
Core Features/Concepts of OOP
-
Objects & Classes: A Class is a blueprint/template; an Object is a concrete instance of that class.
-
Data Encapsulation: Bundling data (attributes) and methods (functions) that operate on the data into a single unit (class). It restricts direct access to some components.
-
Information Hiding: Using
private/protectedaccess specifiers to hide internal implementation details, exposing only a public interface. Encapsulation enables Information Hiding. -
Inheritance: Mechanism where a new class (derived/child) acquires properties and behaviors of an existing class (base/parent). Promotes code reuse.
Key Syntax:
class Derived : access-specifier Base { ... }; -
Polymorphism: "Many forms." Ability of an object to take different forms.
-
Compile-Time (Static): Function/Operator Overloading.
-
Run-Time (Dynamic): Virtual Functions.
-
-
Abstraction: Hiding complex implementation, showing only essential features. Achieved via abstract classes (with pure virtual functions) and interfaces.
Advantages of OOP over Procedural Programming
-
Modularity: Code is organized into classes, making it easier to manage.
-
Reusability: Inheritance allows reuse of existing code.
-
Data Security: Encapsulation & information hiding protect data from accidental modification.
-
Easy Maintenance & Debugging: Changes in one class often don't affect others.
-
Modeling Real-World Systems: Natural mapping to real entities.
Techniques for Handling System Complexity
-
Divide & Conquer: Break complex system into smaller, manageable objects/classes.
-
Abstraction: Focus on what an object does, not how.
-
Encapsulation: Hide internal state, reduce interdependencies.
-
Inheritance Hierarchy: Create logical "is-a" relationships to share common features.
II. C++ AS AN OBJECT-ORIENTED LANGUAGE: BASICS
C++ vs. C Language (Key OOP Extensions)
| Feature | C Language | C++ Language |
|---|---|---|
| Paradigm | Procedural | Multi-paradigm (Procedural + OOP) |
| Data Security | No access control | public, private, protected |
| Functions | Separate from data | Member functions inside classes |
| Reusability | Limited (functions) | High (Inheritance, Polymorphism) |
| I/O | printf/scanf (format-based) |
cin/cout (type-safe, operator-based) |
| Memory | malloc/free |
new/delete (call constructors/destructors) |
| Other | No classes, templates, exceptions | Has classes, templates, exceptions, references |
Variable Declaration & Scope
-
Significance: In C++, variables can be declared anywhere within a scope (block
{ }), not just at the beginning. -
Benefit: Improves readability, reduces unnecessary lifetime of variables, allows initialization at point of use.
for (int i = 0; i < 10; i++) { // i declared in for-loop scope int local = i * 2; // Declared where used }
Structures vs. Classes
| Feature | struct |
class |
|---|---|---|
| Default Access | public |
private |
| Primary Use | Passive data structures (POD) | Full OOP with encapsulation, inheritance |
| Inheritance | Possible (rarely used) | Primary mechanism |
| Member Functions | Allowed, but uncommon | Expected |
| Example | struct Point { int x, y; }; |
class Student { private: int marks; public: void set(); }; |
Input/Output in C++
-
cin/cout(Stream-based):-
Type-safe, no format specifiers needed.
-
Uses overloaded
<<(insertion) and>>(extraction) operators. -
Slower than C I/O due to type checking.
-
-
scanf/printf(Format-based):-
C-style, requires format specifiers (
%d,%f). -
Faster but prone to format-string errors.
-
Not type-safe.
-
Exam Tip:
cin/coutare preferred in C++ for object-oriented design and readability.
III. CLASSES, OBJECTS, AND MEMBER FUNCTIONS
Class Definition & Object Creation
class ClassName {
private: // Data members (hidden)
int data;
public: // Member functions (interface)
void set(int d) { data = d; }
int get() { return data; }
};
ClassName obj1; // Stack object
ClassName* obj2 = new ClassName(); // Heap object
Access Specifiers & Mechanism of Access
| Context | Access to private members |
Access to public members |
|---|---|---|
Inside main() |
❌ Not allowed | ✅ Allowed (via object/pointer) |
| Inside same class's member function | ✅ Allowed | ✅ Allowed |
| Inside another class's member function | ❌ Not allowed (unless friend) |
✅ Allowed (via object/pointer/reference) |
Member Functions
-
Inline Functions:
-
Defined inside class definition (implicitly
inline) or withinlinekeyword outside. -
Purpose: Suggest compiler to replace function call with code body (reduces overhead for small functions).
-
vs. Macros:
| | Inline Functions | Macros | | :--- | :--- | :--- | | Type Safety | ✅ Yes (type-checked) | ❌ No (textual substitution) | | Debugging | ✅ Easier (function call) | ❌ Hard (no symbol) | | Scope | ✅ Respects scope | ❌ Global text substitution | | Return Type | ✅ Must have | ❌ No return type enforcement |
-
-
Static Member Functions & Variables:
-
Static Variable: Shared among all objects. Defined inside class, initialized outside.
class Counter { static int count; // Declaration public: Counter() { count++; } static int getCount() { return count; } // Static member function }; int Counter::count = 0; // Definition & initialization -
Static Function: Can access only static members. Called using
ClassName::func()without object.
-
-
thisPointer:-
Implicit pointer passed to all non-static member functions.
-
Points to the object for which the function is called.
-
Used to disambiguate member names from parameters.
class Box { int length; public: Box& setLength(int length) { this->length = length; // 'this->length' is member, 'length' is parameter return *this; } };
-
Array of Objects
-
Contiguous block of memory storing multiple objects of same class.
-
Constructors called for each element in order.
Student s[3]; // Array of 3 Student objects for(int i=0; i<3; i++) s[i].setRoll(i+1);
Pointers to Objects & Dynamic Creation
-
Syntax:
ClassName* ptr = new ClassName(args); -
Access members:
ptr->memberor(*ptr).member. -
Delete:
delete ptr;(calls destructor, frees memory). -
Array of objects via pointer:
Student* arr = new Student[5]; // Calls default constructor 5 times delete[] arr; // Must use [] to delete array
IV. CONSTRUCTORS AND DESTRUCTORS
Constructor
-
Purpose: Initialize object's data members at creation.
-
Characteristics: Same name as class, no return type, can be overloaded.
-
Types:
-
Default Constructor:
ClassName(); no parameters or all parameters have defaults. -
Parameterized Constructor:
ClassName(int a, float b); -
Copy Constructor:
ClassName(const ClassName& obj);// Takes reference to same class object.// Example & Use: Passing/returning objects by value Complex c1(1,2); Complex c2 = c1; // Copy constructor invoked
-
Constructor Overloading & Chaining
-
Overloading: Multiple constructors with different parameter lists.
-
Chaining: Calling one constructor from another using member initializer list.
class Box { int l, b, h; public: Box() : Box(0,0,0) {} // Chaining to parameterized constructor Box(int x, int y, int z) : l(x), b(y), h(z) {} // Initializer list };
Destructor
-
Purpose: Clean up resources (memory, files) before object is destroyed.
-
Syntax:
~ClassName(); no parameters, no return type. -
Called automatically when object goes out of scope or
deleteis called.
Initializing Base Class Members through Derived Constructor
-
Use member initializer list to call specific base constructor.
class Base { int a; public: Base(int x) : a(x) {} }; class Derived : public Base { int b; public: Derived(int x, int y) : Base(x), b(y) {} // Base(x) initializes base part };
Order of Constructor Calls in Inheritance
-
Base class constructor (most general) called first.
-
Then derived class constructor (most specific).
Rule: Construction happens from general to specific (top-down in hierarchy).
V. INHERITANCE
Concept & Importance
-
Concept: "is-a" relationship. Derived class inherits base class members.
-
Importance: Code reuse, extensibility, logical classification, polymorphism foundation.
Types of Inheritance with Examples
| Type | Description | Example | Complexity/Diamond? |
|---|---|---|---|
| Single | One derived from one base | class B : public A |
No |
| Multilevel | Chain: A → B → C | class C : public B |
No |
| Multiple | One derived from multiple bases | class C : public A, public B |
Yes (Diamond) |
| Hierarchical | Multiple derived from one base | class B : public A, class C : public A |
No |
| Hybrid | Combination (e.g., Hierarchical + Multiple) | class D : public B, public C where B,C inherit from A |
Yes |
Complexity & Ambiguity in Multiple Inheritance
-
Diamond Problem: When a class inherits from two classes that both inherit from a common base, leading to duplicate copies of the base subobject.
class A { public: void f(); }; class B : public A {}; class C : public A {}; class D : public B, public C {}; // D has TWO A subobjects! D.f() ambiguous. -
Resolution:
-
Scope Resolution:
dobj.B::f();ordobj.C::f();(specifies path). -
Virtual Base Classes: Declare base as
virtualin intermediate classes.class B : virtual public A {}; // Only ONE shared A subobject in D class C : virtual public A {}; class D : public B, public C {}; // No ambiguity
-
Access Specifiers in Inheritance
| Base Member | public Inheritance |
protected Inheritance |
private Inheritance |
|---|---|---|---|
public |
public in Derived |
protected in Derived |
private in Derived |
protected |
protected in Derived |
protected in Derived |
private in Derived |
private |
Not accessible | Not accessible | Not accessible |
Constructors in Inheritance (Order)
-
Base class constructor (in order of inheritance declaration).
-
Member object constructors (in order of declaration in class).
-
Derived class constructor body.
Exam Tip: Destruction order is exact reverse: Derived destructor → Member objects → Base destructor.
VI. POLYMORPHISM
Compile-Time Polymorphism (Static Binding)
-
Function Overloading: Multiple functions with same name but different parameter lists (type/number/order).
-
Rules: Return type cannot be the only difference.
-
Example:
int Max(int a, int b); float Max(float a, float b); string Max(string a, string b);
-
-
Operator Overloading:
-
Syntax:
// As member function (1 parameter for binary, 0 for unary) ReturnType operator+(const ClassName& obj); // As non-member/friend (2 parameters for binary) friend ReturnType operator+(const ClassName& a, const ClassName& b); -
Example (Unary
-):Complex operator-() { return Complex(-re, -im); } -
Pros: Intuitive syntax for user-defined types.
-
Cons: Can make code confusing if misused; cannot change operator precedence.
-
Run-Time Polymorphism (Dynamic Binding)
-
Virtual Functions:
-
Declared with
virtualkeyword in base class. -
Vtable (Virtual Table): Compiler-generated table of function pointers for each class with virtual functions. Enables late binding.
-
Mechanism: Call via base class pointer/reference resolves to derived class's overridden version at runtime.
-
-
Pure Virtual Functions & Abstract Classes:
-
Syntax:
virtual void func() = 0; -
Abstract Class: Contains at least one pure virtual function. Cannot instantiate objects of abstract class.
-
Purpose: Define interface/template for derived classes.
-
-
Achieving Runtime Polymorphism:
class Shape { public: virtual void area() = 0; }; class Rect : public Shape { public: void area() override { /*...*/ } }; Shape* ptr = new Rect(); ptr->area(); // Calls Rect::area() at runtime
Comparison: Runtime vs. Compile-time Polymorphism
| Feature | Compile-Time (Overloading) | Run-Time (Virtual) |
|---|---|---|
| Binding Time | Compile time | Runtime |
| Mechanism | Same function name, different signatures | virtual keyword, vtable |
| Speed | Faster (static) | Slower (dynamic lookup) |
| Inheritance Required? | No | Yes |
| Flexibility | Less | More (can add new derived classes without recompiling client code) |
Binding: Early vs. Late
-
Early (Static) Binding: Function call resolved at compile time. (e.g., non-virtual, overloaded functions).
-
Late (Dynamic) Binding: Function call resolved at runtime using vtable. (e.g., virtual functions via pointer/reference).
VII. FUNCTION TEMPLATES
Concept & Syntax
-
Purpose: Write generic code that works with any data type.
-
Syntax:
template <typename T> // or 'class T' T Max(T a, T b) { return (a > b) ? a : b; } // Usage: Max(10, 20); Max(3.14, 2.71); Max('a', 'z');
Overloaded Function Templates
-
Template can be overloaded with other templates or non-template functions.
-
Compiler chooses the most specific match.
template <typename T> T Max(T a, T b) { /* ... */ } template <typename T, typename U> auto Max(T a, U b) -> decltype(a+b) { /* ... */ } // Overloaded for different types int Max(int a, int b); // Non-template overload (most specific for ints)
VIII. EXCEPTION HANDLING
Mechanism & Keywords
-
tryblock: Encloses code that might throw an exception. -
throwexpression: Signals an error condition (can throw any type: int, string, object). -
catchblock: Handles exception of a specific type.try { // risky code if (error) throw "Division by zero!"; else throw runtime_error("Invalid input"); } catch (const char* msg) { // catches string cout << msg << endl; } catch (const runtime_error& e) { // catches standard exception cout << e.what() << endl; } catch (...) { // catches any exception (last resort) cout << "Unknown error" << endl; }
Standard Exception Classes (<stdexcept>)
-
logic_error,invalid_argument,out_of_range,runtime_error,overflow_error, etc. -
All inherit from
std::exception; havewhat()method returning C-string description.
Synchronous vs. Asynchronous Exceptions
| Synchronous Exceptions | Asynchronous Exceptions | |
|---|---|---|
| Source | Program-controlled (within try block) |
External events (hardware, OS signals) |
| Handling | ✅ Handled by catch blocks |
❌ Not handled by C++ catch (bypasses normal flow) |
| Example | throw statement, new (bad_alloc) |
Keyboard interrupt (Ctrl+C), segmentation fault |
| C++ Mechanism | Yes (designed for) | No (requires OS/hardware handling) |
IX. ADVANCED FEATURES & SPECIAL FUNCTIONS
Friend Functions & Friend Classes
-
Purpose: Grant non-member function or entire class access to
private/protectedmembers of another class. -
Syntax:
class A { private: int secret; friend void reveal(const A&); // Friend function declaration friend class B; // Friend class declaration }; void reveal(const A& a) { cout << a.secret; } // Can access private -
Use Cases: Operator overloading (binary operators), tightly coupled classes.
Static Members (Recap)
-
Static Variable: One copy shared by all objects.
static int count; -
Static Function: Can be called without object (
ClassName::func()). Can access only static members.
const Member Functions
-
Declared with
constafter parameter list:int get() const; -
Promise: Does not modify any non-
mutabledata members. -
Can be called on
constobjects.
X. MEMORY MANAGEMENT
Dynamic Memory Allocation
-
new: Allocates memory on heap, calls constructor.int* p = new int(5); // single int Student* s = new Student("Rahul", 20); // object int* arr = new int[10]; // array -
delete: Calls destructor, frees memory.delete p; delete s; delete[] arr; // Must match `new[]`
malloc/free vs. new/delete
new/delete |
malloc/free |
|
|---|---|---|
| Type | Operator (language keyword) | Function (C library <cstdlib>) |
| Constructor/Destructor | ✅ Calls them | ❌ Does not call |
| Return Type | Returns typed pointer (T*) |
Returns void* (needs cast) |
| Size Calculation | Automatic (from type) | Manual (sizeof) |
| C++ Preferred? | Yes (object-oriented) | No (C-style) |
Memory Leaks & Debugging Pointers
-
Memory Leak: Allocated memory (
new) not deallocated (delete). Lost pointer. -
Dangling Pointer: Pointer pointing to deleted memory.
int* p = new int(5); delete p; *p = 10; // ERROR! Dangling pointer -
Wild Pointer: Uninitialized pointer (contains garbage address).
-
Prevention: Initialize pointers to
nullptr, set tonullptrafterdelete, use smart pointers (unique_ptr,shared_ptr). -
nullptr: Type-safe null pointer constant (C++11). Prefer overNULL/0.
XI. PRACTICAL PROGRAMMING APPLICATIONS (Key Patterns)
Class Design with Validation
class Student {
int marks;
public:
void setMarks(int m) {
if (m >= 65 && m <= 100) marks = m;
else throw invalid_argument("Marks must be 65-100");
}
};
Inheritance & Constructor Initialization
class Person {
string name;
public:
Person(string n) : name(n) {} // No default constructor
};
class Employee : public Person {
double salary;
public:
Employee(string n, double s) : Person(n), salary(s) {} // Explicit base call
};
Polymorphic Program Design
class Shape {
public:
virtual void area() = 0; // Pure virtual
};
class Rect : public Shape {
float l, b;
public:
void area() override { cout << l*b; }
};
class Circle : public Shape {
float r;
public:
void area() override { cout << 3.14*r*r; }
};
// Client code:
Shape* shapes[2] = {new Rect(2,3), new Circle(5)};
for(int i=0; i<2; i++) shapes[i]->area(); // Late binding
XII. FILE I/O
File Stream Classes (<fstream>)
-
ifstream: Input file stream (read). -
ofstream: Output file stream (write). -
fstream: Both read/write.
Opening/Closing & Operations
ofstream fout("output.txt"); // Open for writing
if (!fout.is_open()) { /* error */ }
fout << "Data " << 123 << endl; // Write
fout.close();
ifstream fin("input.txt");
string line;
while (getline(fin, line)) { // Read line by line
cout << line << endl;
}
fin.close();
Error Handling
-
is_open(): Check if file opened successfully. -
fail(),bad(): Check stream state after operation. -
eof(): Check end-of-file reached.
UNIT 2 EXAM STRATEGY:
- High-Frequency Topics: Inheritance (types, diamond problem), Polymorphism (virtual, abstract), Constructors (order, copy), Templates, Exception Handling.
- Code-Based Questions: Be ready to write complete programs for:
* Array of objects (Dec 24 Q3)
* Copy constructor (Dec 24 Q6)
* Runtime polymorphism (Dec 24 Q11)
* Operator overloading (Dec 23 Q4)
* File I/O (Dec 23 Q15)
- Theory Questions: Distinguish concepts clearly (e.g., Compile vs Runtime polymorphism, Abstract vs Non-abstract class, Encapsulation vs Information Hiding).
- Common Pitfalls:
* Forgetting `virtual` destructor in polymorphic base class.
* Mismatching `new[]` with `delete` (not `delete[]`).
* Ambiguity in multiple inheritance without `virtual` or scope resolution.
* Calling virtual functions from constructors (binds to base version, not derived).