Docsity

OOPs Notes for Software engineers, Study notes of Software Engineering

Partial preview of the text

Download OOPs Notes for Software engineers and more Study notes Software Engineering in PDF only on Docsity!

Object-Oriented Programming in C++

Interview Notes & Revision Handbook — Compiled from Source Code Analysis

Compiled Study Handbook

July 18, 2026

Contents

Object-Oriented Programming in C++

Interview Notes & Revision Handbook

Compiled from a C++ OOP Source Code Sample

Covers:

Encapsulation • Constructors & the this Pointer • Inheritance

Polymorphism (Compile-Time & Run-Time) • Abstraction

Destructors • Static Members • Friend Functions • Composition

Complete OOP Concept Cheat Sheet

Prepared for Placements, Coding Interviews & GATE Revision

July 18, 2026

Chapter 1

How to Use This Handbook

This handbook was generated by analyzing a C++ source file that demonstrates the four pillars of Object-

Oriented Programming — Encapsulation , Inheritance , Polymorphism , and Abstraction — through small

example classes, with comments explaining the intent behind each one.

Each concept is documented using a consistent template:

  • What It Solves — the problem the concept addresses, in plain language
  • How It Works — the thought process and mechanics behind the concept
  • Code — the exact code from the source file, or a added example where the source file only described a

concept without demonstrating it

  • Trace / Example Output — what the code actually does when run, worked through step by step
  • Key Points — interview traps, edge cases, common mistakes, and important terminology
  • Related / Alternative Concepts — how this concept connects to or contrasts with others

Two real bugs were found in the source’s constructor/setter logic (both involving the this pointer) — con-

firmed by compiling and running the code — and are flagged inline with corrected versions, plus consolidated

in the Code Review appendix.

Several important OOP concepts were referenced only in a comment, or not mentioned at all , in the

original source — these have been added in full, with original example code, so this handbook is a complete

pillar-by-pillar reference rather than just a copy of what was written. These additions are clearly marked as

such throughout. The handbook closes with a Master Concepts Table and a Complete OOP Interview

Cheat Sheet.

OOP in C++ — Interview Notes CHAPTER 2. ENCAPSULATION
  • The getters and setters pattern (shown in the next chapter’s Student class) is the standard way to expose

controlled access to otherwise-private data — e.g. a setter can validate a value before assigning it, which

direct public access would bypass entirely.

  • Encapsulation is what makes refactoring safe : if password were public and read directly all over a large

codebase, changing how it’s stored (e.g. hashing it) would require finding and fixing every direct access.

With it private and accessed only through member functions, only the class itself needs to change.

Related / Alternative Concepts

Access control is also enforced across inheritance boundaries by the specifier used when inheriting (public,

protected, or private inheritance) — this is a distinct and commonly confused concept, covered in depth

in the Inheritance chapter.

2.1 Access Specifiers — Quick Reference

Specifier

Accessible Inside Same

Class

Accessible in Derived

Class

Accessible Outside (via

object)

public Yes Yes Yes

protected Yes Yes No

private Yes No No

Chapter 3

Constructors, the this Pointer, and Destruc-

tors

3.1 Constructors

What It Solves

An object often needs to start life in a valid, fully-initialized state — data members shouldn’t sit uninitialized

(containing garbage values) after creation. A constructor solves this by running automatically, exactly once ,

the moment an object is created, guaranteeing initialization code always executes without the caller having

to remember to call it.

How It Works

A constructor is a special member function that shares its class’s exact name , has no return type (not even

void), and is invoked implicitly by the compiler at the point of object creation. C++ supports constructor

overloading — multiple constructors with different parameter lists can coexist, and the compiler picks the

right one based on how the object is created. This makes constructors a form of compile-time polymorphism

in their own right, even though the source groups only function/operator overloading under that heading.

Code

class Student { public: string name ; int age ; string department ;

// CONSTRUCTOR - same name as class, used for initialisation, three types below, // called only once at object creation, automatically by the compiler Student (){ // non-parameterised constructor -> no parameters passed age = 18 ; }

Student ( string department ){ // parameterised constructor -> parameters passed department = this-> department ; } };

Trace / Example Output

  • Student s1; → invokes the non-parameterized constructor → s1.age becomes 18 ; s1.name and

s1.department remain uninitialized (garbage/empty, since string default-constructs to "", but int age

for s2 below would be genuinely uninitialized garbage if that constructor didn’t set it).

  • Student s2("CSE"); → invokes the parameterized constructor. This is where a real bug shows up —

see Key Points.

OOP in C++ — Interview Notes CHAPTER 3. CONSTRUCTORS, THE THIS POINTER, AND DESTRUCTORS

ment member of the current object” — this is a pointer, so it’s dereferenced with -> (or manually with * and

Code

void setDept ( string department ){ // known as a setter function, sets a data member's value department = this-> department ; // this-> in this part is a pointer referring to the parameter passed into the function // when it has the same name as the data member; can also use *(this).department }

string getName (){ // known as a getter function, returns a data member's value return name ; }

Trace / Example Output

Student s; s.setDept("CSE"); cout << s.department; → prints an empty string.

Key Points — Confirmed Bug (Same Pattern as the Constructor)

Exactly like the parameterized constructor above, setDept has the assignment backwards : department =

this->department; copies the (empty) member value into the local parameter, which then simply goes out

of scope and is discarded — the object’s department is never actually updated. Verified by compiling and

running: after s.setDept("CSE"), s.department remains "".

Corrected version:

void setDept ( string department ){ this-> department = department ; // FIX }

  • getName() has no such bug — since its local scope has no variable named name shadowing the member,

return name; unambiguously refers to the member. this is only required for disambiguation when a

shadowing name exists; it can always be used even when not required, purely for clarity.

  • This shadowing pattern (parameter name identical to member name) is an extremely common real-world

style choice specifically because this-> cleanly resolves the ambiguity — but as shown here, it’s also

an easy place to introduce exactly this class of bug. Always be deliberate about which side of = you’re

writing.

3.3 Destructors — (Added: not present in the original source)

What It Solves

Just as a constructor guarantees setup code runs at creation, a destructor guarantees cleanup code runs auto-

matically when an object’s lifetime ends — critical for releasing resources the object acquired (dynamically

allocated memory, open files, network handles, locks) so they aren’t leaked.

How It Works

A destructor shares the class’s name prefixed with ~, takes no parameters , cannot be overloaded (a class

has exactly one destructor), and is called automatically: when a stack-allocated object goes out of scope, or

explicitly via delete for a heap-allocated object created with new.

OOP in C++ — Interview Notes CHAPTER 3. CONSTRUCTORS, THE THIS POINTER, AND DESTRUCTORS

Code — (Added Example)

class Student { public: string name ; int ***** scoresPtr ; // dynamically allocated resource

Student ( string n ) { name = n ; scoresPtr = new int [ 10 ]; // acquire a resource }

~ Student (){ // destructor delete[] scoresPtr ; // release the resource cout << "Destructor called for " << name << endl ; } };

Trace / Example Output

void demo (){ Student s ( "Aditi" ); cout << "Inside function" << endl ; } // s goes out of scope here -> destructor runs automatically

Output:

Inside function
Destructor called for Aditi

Key Points

  • If a class allocates a resource in its constructor (like new int[10] above) and has no destructor , that

memory is leaked every time an object of that class is destroyed — this is exactly the kind of gap worth

flagging: the original Student class in the source has no dynamically allocated members, so it happens

not to need a custom destructor, but any class that does needs one.

  • The compiler generates a default destructor if none is written, which correctly destroys all member

objects (calling their destructors) but does nothing for raw pointers — it will not call delete on a raw

pointer member. This is precisely why classes that hold raw owning pointers must define their own

destructor.

  • Virtual destructors matter enormously for polymorphic classes — covered in the Polymorphism chapter,

since it directly connects to a classic interview bug: deleting a derived object through a base class pointer

without a virtual base destructor causes undefined behavior (typically only the base part is destroyed,

leaking the derived part).

3.4 Copy Constructor — (Added: only referenced in the source’s comments,

not implemented)

What It Solves

OOP in C++ — Interview Notes CHAPTER 3. CONSTRUCTORS, THE THIS POINTER, AND DESTRUCTORS
  • Passing objects by value into functions invokes the copy constructor implicitly — a subtle performance

and correctness trap for large objects or classes with owning pointers; passing by const& avoids the copy

entirely when the function doesn’t need to modify or store its own copy.

3.5 Rule of Three / Rule of Five — (Added)

What It Solves

A guideline for knowing when the compiler-generated special member functions are unsafe to rely on.

How It Works

Rule of Three : if a class needs a custom destructor , copy constructor , or copy assignment operator ,

it almost certainly needs all three — because needing any one of them is a signal that the class manages a

resource the compiler’s shallow defaults would handle incorrectly. Rule of Five extends this for modern C++

(C++11+) to also include the move constructor and move assignment operator , which allow a resource to

be transferred (not copied) from a temporary object efficiently.

Key Points

  • Classes that only contain “plain” members (ints, strings, vectors, other well-behaved objects) generally

don’t need any of these written manually — the compiler defaults compose correctly member-by-member.

It’s specifically ownership of a raw resource (a pointer from new, a file handle, etc.) that triggers the

Rule of Three/Five.

  • Modern C++ style often prefers avoiding raw owning pointers altogether — using std::unique_ptr/std::shared_ptr

(smart pointers) or standard containers instead — which sidesteps the Rule of Three/Five entirely, since

those types already implement correct copy/move/destroy semantics themselves. Worth mentioning as

the modern best practice when this topic comes up.

Chapter 4

Inheritance

What It Solves

Many classes share common structure — rather than re-writing the same members and functions in every

related class, inheritance lets a new class ( derived / child ) automatically acquire the members and functions

of an existing class ( base / parent ), then add or change only what’s different. This solves code duplication

and models real-world “is-a” relationships (a Faculty is a Human).

How It Works

A derived class lists its base class after a colon, with an access specifier (usually public) controlling how

the base’s members are exposed through the derived class. All of the base’s public and protected members

become part of every derived object’s layout and behavior — private members exist in memory too, but

remain permanently inaccessible to the derived class’s own code, only reachable indirectly through the base

class’s own public/protected functions.

Code

class human { public: string status ; // alive or dead };

class faculty : public human { // inherited status from human (base class) into faculty (derived ↪ class) public: string name ; };

Trace / Example Output

faculty f ; f. status = "alive" ; // accessible - inherited public member from human f. name = "Dr. Rao" ; // faculty's own member

A faculty object’s memory layout effectively contains both status (from human) and name (its own) —

inheritance is fundamentally about composing a larger object out of a smaller one, plus extra parts.

Key Points

  • Terminology check : the source’s comment says “properties and members of base/child class can be

passed on to parent/derived class” — this has the direction reversed. The correct direction is: members

flow from the base/parent class down to the derived/child class , not the other way around. Always

double check this direction when explaining inheritance in an interview — getting it backwards is a

common slip under pressure.

OOP in C++ — Interview Notes CHAPTER 4. INHERITANCE

When hybrid or multiple inheritance causes a class to inherit from the same base class through two different

paths (as teachingAssistant does above — via both faculty and student, which both inherit from human),

the derived class ends up with two separate copies of human’s members. This is ambiguous: ta.status

doesn’t compile, because the compiler can’t tell whether you mean the copy that arrived via faculty or the

one via student.

How It’s Solved

Virtual inheritance — inheriting from the shared base using the virtual keyword — tells the compiler to

keep only one shared copy of that base, no matter how many paths lead to it.

class human { public: string status ; }; class faculty : virtual public human { public: string department ; }; class student : virtual public human { public: string rollNumber ; }; class teachingAssistant : public faculty , public student { }; // now unambiguous

teachingAssistant ta ; ta. status = "alive" ; // compiles - only one shared human subobject exists

Key Points

  • The Diamond Problem is one of the most-cited reasons some languages (like Java) disallow multiple

inheritance of classes entirely , instead only allowing multiple inheritance of interfaces — a great point

of comparison to raise in interviews.

  • virtual inheritance solves ambiguity but adds runtime overhead (the shared base’s location must be

looked up indirectly) — not something to reach for by default, only when the diamond shape is unavoid-

able in the design.

4.3 Access Specifier of Inheritance — (Added: the source always used public, without explaining the alternatives)

The keyword before the base class name (public, protected, or private) controls how the base’s members

are re-exposed through the derived class — this is a separate concept from the access specifiers inside a

class body, and is frequently confused with it.

Base Member Was… public Inheritance protected Inheritance private Inheritance

public stays public becomes protected becomes private

protected stays protected stays protected becomes private

private inaccessible either way inaccessible either way inaccessible either way

  • public inheritance (used throughout the source, and the overwhelming majority of real-world usage)

models a true “is-a” relationship, and is the default assumption unless a problem specifically calls for the

others.

  • private/protected inheritance are rare, used to model “implemented-in-terms-of” relationships without

exposing an “is-a” relationship to outside code — worth knowing exist, but citing public as the default

correct answer unless told otherwise is the safe interview response.

OOP in C++ — Interview Notes CHAPTER 4. INHERITANCE

4.4 Constructor & Destructor Order in Inheritance — (Added)

Key Points

  • When a derived object is created, the base class’s constructor runs first , automatically, before the de-

rived class’s own constructor body executes — this guarantees the base portion of the object is fully valid

before the derived portion starts building on top of it.

  • Destructors run in the exact opposite order : the derived class’s destructor runs first, then the base

class’s destructor — cleaning up in the reverse order that things were built, exactly like unwinding a

stack.

  • A derived constructor can explicitly choose which base constructor to invoke via the member initializer

list: faculty(string s) : human(s) {} — if omitted, the base’s default (no-argument) constructor is

called automatically instead.

OOP in C++ — Interview Notes CHAPTER 5. POLYMORPHISM

Note 65 and 'A' represent the same underlying byte value in ASCII, yet produce entirely different output — a

clean illustration that overload resolution is based on the declared type of the argument , not its underlying

value.

Key Points

  • Overloads must differ in their parameter list (types, count, or order) — differing only in return type is

not enough and will not compile (int show(); char show(); is an ambiguous redeclaration, not a valid

overload pair).

  • Overload resolution can fail with an ambiguous call error if two overloads are equally good matches

after implicit conversions (e.g. calling show(65.0) — a double — when only show(int) and show(char)

exist forces an implicit conversion to one or the other, and if both conversions are considered equally

valid, the compiler can’t choose and refuses to compile).

5.2 Compile-Time Polymorphism: Operator Overloading — (Added: men-

tioned by name in the source’s comment, but never demonstrated)

What It Solves

Lets built-in operators (+, - , ==, <<, etc.) be given meaningful behavior for user-defined types , so objects can

be combined or compared with the same natural syntax used for built-in types, instead of requiring awkward

named functions like p1.add(p2).

How It Works

An operator is overloaded by defining a specially-named function — operator+, operator==, etc. — either

as a member function of the class, or as a standalone (often friend) function when the left-hand operand

isn’t an object of the class (as is the case for operator<< with cout).

Code — (Added Example)

class Point { public: int x , y ; Point ( int x = 0 , int y = 0 ) : x ( x ), y ( y ) {}

Point operator+( const Point & other ){ // overloading the + operator return Point ( x + other. x , y + other. y ); }

bool operator==( const Point & other ){ // overloading the == operator return ( x == other. x ) && ( y == other. y ); } };

Trace / Example Output

Point p1 ( 1 , 2 ), p2 ( 3 , 4 ); Point p3 = p1 + p2 ; // calls operator+ -> p3 = (4, 6) cout << ( p1 == p2 ) << endl ; // calls operator==, prints: 0 (false)

Key Points

OOP in C++ — Interview Notes CHAPTER 5. POLYMORPHISM
  • Some operators cannot be overloaded at all in C++ — notably :: (scope resolution),. (member access),

.*, sizeof, and the ternary ?:. Interviewers occasionally ask which operators are off-limits, precisely

because it’s an easy fact to have never encountered.

  • Overloading == without also overloading != (or vice versa) is a common oversight; modern C++ (C++20)

allows the compiler to auto-derive != from ==, but relying on that isn’t safe across all compiler versions.

  • This is still classified as compile-time polymorphism, exactly like function overloading, because the

compiler determines which operator+ (or whichever operator) to call based on the static types of the

operands, before the program runs.

5.3 Run-Time Polymorphism: Function Overriding

What It Solves

Lets a base-class pointer or reference call a function and have the derived class’s version actually run ,

even though the compiler, at compile time, only knows it’s dealing with “some kind of base class object” —

the concrete type isn’t resolved until the program is running. This is what allows one piece of generic code

(e.g. a loop over a collection of Animal*) to correctly invoke each object’s own specific behavior.

How It Works

Marking a base class function virtual tells the compiler to defer the decision of which version to call until

run time, using a mechanism (conceptually a vtable — a per-class table of function pointers, and a hidden

vptr in each object pointing to its class’s table) to look up the correct function based on the object’s actual

type — not the type of the pointer/reference used to access it. The derived class then overrides that function

by redefining it with an identical signature.

Code

class Parent { // example of function overriding public: virtual void display () { cout << "This is Parent class." << endl ; } };

class Child : public Parent { // function overriding is basically redefining the function public: void display () override { cout << "This is Child class." << endl ; } };

Trace / Example Output

Parent ***** p = new Child (); p -> display (); // prints: "This is Child class." -- NOT "This is Parent class." delete p ;

Even though p is declared as Parent*, the actual object it points to is a Child, so the virtual dispatch mecha-

nism correctly calls Child::display() at run time. Without the virtual keyword on the base’s display(),

this same code would incorrectly print "This is Parent class." — resolved at compile time based purely

on the pointer’s declared type, ignoring the real object.