Unit 1

OOP Fundamentals

Classes, Objects, Encapsulation, Inheritance, Polymorphism & Abstraction — from zero to exam-ready

← Home
01
OOAD
02
OOP Basics
03
Encapsulation
04
Inheritance
05
Polymorphism
06
Abstraction
07
Classes & Objects
08
Access Specifiers
09
Methods
10
I/O Operations
11
Data Types & Variables
12
Control & Loops & Arrays
13
UML Diagrams
C++Compiler
01

OOAD — Object-Oriented Analysis and Design

Real-Life AnalogyBefore building a house, an architect first analyzes what rooms are needed (OOA) and then designs the blueprint (OOD). OOAD works the same way for software.

What is OOAD?

OOAD is a software development approach that models a system as a collection of objects representing real-world entities. It has two phases:

Phase 1 — Object-Oriented Analysis (OOA)

Focuses on WHAT the system should do. Identifies objects, classes, attributes, and relationships. Example: For a Library System, objects are Book, Member, Librarian.

Phase 2 — Object-Oriented Design (OOD)

Focuses on HOW the system will be built. Defines class structure, methods, and interactions. Example: Design methods like issueBook(), returnBook() for the Member class.

Key Concepts Used in OOAD

Concept Meaning
Encapsulation Hiding data inside objects
Inheritance Reusing existing classes
Polymorphism Same method, different behavior
Abstraction Showing only essential features
Exam Answers

2-mark: OOAD is a methodology to analyze and design software by modeling real-world entities as objects with attributes and behaviors.

5-mark: OOAD has two phases — OOA identifies classes, attributes, and relationships from the problem domain; OOD converts these into a programmable design using class structures and method interactions. It uses four key principles: Encapsulation, Inheritance, Polymorphism, and Abstraction. Advantages include improved reusability, maintainability, and scalability.

#include <iostream>
using namespace std;

// OOA: Objects = Book, Member
// OOD: Design classes and methods
class Book {
public:
    string title;
    bool available;
    Book(string t) { title = t; available = true; }
};

class Member {
public:
    string name;
    void issueBook(Book &b) {
        if (b.available) {
            b.available = false;
            cout << name << " issued: " << b.title << endl;
        } else {
            cout << "Book not available!" << endl;
        }
    }
    void returnBook(Book &b) {
        b.available = true;
        cout << name << " returned: " << b.title << endl;
    }
};

int main() {
    Book b1("C++ Primer");
    Member m1;
    m1.name = "Arun";
    m1.issueBook(b1);   // success
    m1.issueBook(b1);   // fail - already issued
    m1.returnBook(b1);  // returned
    return 0;
}
► Expected Output
Arun issued: C++ Primer Book not available! Arun returned: C++ Primer
1
OOA Phase: We identified real-world objects: Book (has title, availability) and Member (has name, can borrow).
2
OOD Phase: We designed the structure. Book stores state; Member provides behavior (methods).
3
The issueBook method uses logic to protect the book's available state.
4
In main, we create instances (b1, m1) and simulate the library workflow.
5
Notice how objects interact: m1.issueBook(b1) passes the book object to the member's method.
#include <iostream>
using namespace std;
class Book { public: string title; bool available; Book(string t){title=t; available=true;} };
class Member { public: string name; void issueBook(Book &b){ if(b.available){ b.available=false; cout<<name<<" issued: "<<b.title<<endl; } else cout<<"Not available!"<<endl; } };
int main(){ Book b1("C++ Primer"); Member m1; m1.name="Arun"; m1.issueBook(b1); m1.issueBook(b1); return 0; }
► Expected Output
Arun issued: C++ Primer Not available!
1
Analytic Phase (OOA): Identify entities like Book and Member.
2
Design Phase (OOD): Define how they interact.
3
Logic handles state (availability) inside Member's method.
🔨 Build From Scratch — OOAD
// OOA/OOD Demo
class Book { public: string title; };
► Expected Output
1
Analysis identifies entities.
2
Design defines structure.
Memory LockOOA = WHAT to build | OOD = HOW to build | Together = OOAD
Think: Architect (OOA=requirements, OOD=blueprint)

02

OOP — Object-Oriented Programming Basics

Real-Life AnalogyA Car is an object. Its attributes: color, speed, model. Its behaviors: start(), stop(), accelerate(). OOP programs the world this way.

What is OOP?

OOP is a programming approach where software is designed using objects that represent real-world entities. An object contains data (attributes) and behavior (methods).

Four Pillars of OOP

1. Class — Blueprint

A class is a template for creating objects. It defines what data and methods an object will have.

2. Object — Instance

An object is a specific instance created from a class. Each object has its own data.

3. Encapsulation

Bundling data and methods together and restricting direct access. Data is hidden; access is through methods.

4. Inheritance

A child class acquires properties and methods of a parent class, enabling code reuse.

5. Polymorphism

Same method name works differently for different objects.

6. Abstraction

Showing only essential features and hiding internal implementation details.

Complete Program — Your First OOP Program

#include <iostream>
using namespace std;

class Car {
public:
    string color;
    int speed;

    void start() {
        cout << "Car started! Color: " << color << endl;
    }
    void accelerate(int s) {
        speed = s;
        cout << "Speed: " << speed << " km/h" << endl;
    }
};

int main() {
    Car c1;          // Create object
    c1.color = "Red";
    c1.start();
    c1.accelerate(80);
    return 0;
}
► Expected Output
Car started! Color: Red Speed: 80 km/h
#include <iostream>
using namespace std;

class Dog {
public:
    string name;
    int age;

    void bark() {
        cout << name << " says: Woof!" << endl;
    }
    void info() {
        cout << "Name: " << name << ", Age: " << age << endl;
    }
};

int main() {
    Dog d1, d2;        // Two separate objects
    d1.name = "Rex"; d1.age = 3;
    d2.name = "Max"; d2.age = 5;

    d1.bark(); d1.info();
    d2.bark(); d2.info();
    return 0;
}
► Expected Output
Rex says: Woof! Name: Rex, Age: 3 Max says: Woof! Name: Max, Age: 5
1
Class: Dog is the blueprint. It doesn't take memory until an object is made.
2
Object: d1 and d2 are instances. Each has its OWN name and age.
3
Dot Operator: Used to access members. d1.name sets only d1's data.
4
Methods like bark() use the data of the specific object they were called on.
5
This demonstrates Encapsulation: data (name) and behavior (bark) are bundled together.
#include <iostream>
using namespace std;
class Dog {            // blueprint
public:
    string name; int age;
    void bark(){ cout<<name<<" says: Woof!"<<endl; }
    void info(){ cout<<"Name: "<<name<<", Age: "<<age<<endl; }
};
int main(){
    Dog d1, d2;        // two separate objects
    d1.name="Rex"; d1.age=3;
    d2.name="Max"; d2.age=5;
    d1.bark(); d1.info();
    d2.bark(); d2.info();
    return 0;
}
► Expected Output
Rex says: Woof! Name: Rex, Age: 3 Max says: Woof! Name: Max, Age: 5
1
Class = Blueprint: class Dog defines attributes (name,age) and methods (bark(),info()). No memory allocated yet.
2
Object = Instance: Dog d1, d2 creates two dogs. Each gets its own copy of name and age in memory.
3
d1.name="Rex" stores 'Rex' in d1's memory. d2 is unaffected.
4
d1.bark() — inside bark(), name refers to d1's name (Rex). Output: Rex says: Woof!
5
d2 has its own name 'Max' — same method, different data. This is the core of OOP: objects share behaviour but own their data.
#include <iostream>
using namespace std;
class Dog { public: string name; void bark(){ cout<<name<<" says Woof!"<<endl; } };
int main(){ Dog d; d.name="Rex"; d.bark(); return 0; }
► Expected Output
Rex says Woof!
1
Create a class (blueprint).
2
Instantiate an object.
3
Access members using dot operator.
🔨 Build From Scratch — OOP Basics
class Dog { public: string name; void bark(){ cout<<"Woof"; } };
► Expected Output
Woof
1
Class is blueprint.
2
Object is instance.
Memory LockOOP = Class (blueprint) + Object (instance) + 4 Pillars (EIPA)
EIPA = Encapsulation, Inheritance, Polymorphism, Abstraction

Quick Check (click to reveal)

What is the difference between a class and an object?
A class is a blueprint/template. An object is an actual instance created from that blueprint. Example: Car is a class; your specific red car is an object.
Name the 4 pillars of OOP.
Encapsulation, Inheritance, Polymorphism, Abstraction (EIPA)

03

Encapsulation

Real-Life AnalogyA medicine capsule hides chemicals inside. You just swallow it — you don't see or touch the chemicals inside. Similarly, encapsulation hides data inside a class.

Definition

Encapsulation means binding data (variables) and methods together inside a class and restricting direct access to the data. Data is made private and accessed only through public methods.

Real-Life Examples

1. Bank ATM

Data hidden: Account balance, PIN. Methods: withdraw(), deposit(), checkBalance(). You cannot access balance directly — only through ATM options.

2. Mobile Phone

Data hidden: Internal hardware, software code. Methods: Touch screen, buttons, apps. User uses functions without knowing internal workings.

3. Car

Data hidden: Engine, fuel system. Methods: Start, brake. Driver controls car without knowing engine details.

Complete Program

#include <iostream>
using namespace std;

class BankAccount {
private:
    string owner;
    double balance;   // hidden — cannot access directly

public:
    BankAccount(string n, double b) {
        owner = n;
        balance = b;
    }
    void deposit(double amt) {
        if (amt > 0) balance += amt;
        cout << "Deposited: " << amt << " | Balance: " << balance << endl;
    }
    void withdraw(double amt) {
        if (amt <= balance) {
            balance -= amt;
            cout << "Withdrawn: " << amt << " | Balance: " << balance << endl;
        } else {
            cout << "Insufficient funds!" << endl;
        }
    }
    void display() {
        cout << "Account: " << owner << " | Balance: " << balance << endl;
    }
};

int main() {
    BankAccount acc("Alice", 1000.0);
    acc.display();
    acc.deposit(500);
    acc.withdraw(200);
    // acc.balance = 99999;  // ERROR! private member
    return 0;
}
► Expected Output
Account: Alice | Balance: 1000 Deposited: 500 | Balance: 1500 Withdrawn: 200 | Balance: 1300
1
balance is private — cannot be changed from outside the class directly.
2
deposit() and withdraw() are public — they are the only controlled ways to access balance.
3
Trying acc.balance = 99999 outside the class gives a compile error — that's encapsulation protecting the data.
Exam Answer — 5 marks

Encapsulation is the process of bundling data and methods inside a class and restricting direct access to data by making it private. Data can only be accessed through public member functions (getters/setters). This provides data hiding and security. Example: In a BankAccount class, balance is private and can only be modified through deposit() and withdraw() methods. This prevents unauthorized modification of data.

#include <iostream>
using namespace std;

class Student {
private:
    int marks;          // Hidden from outside
public:
    void setMarks(int m) {
        if (m >= 0 && m <= 100)
            marks = m;
        else
            cout << "Invalid marks!" << endl;
    }
    int getMarks() { return marks; }
};

int main() {
    Student s;
    s.setMarks(85);     // Valid input
    cout << "Marks: " << s.getMarks() << endl;
    s.setMarks(150);    // Invalid input - rejected
    // s.marks = 90;    // ERROR: Private!
    return 0;
}
► Expected Output
Marks: 85 Invalid marks!
1
private: makes marks inaccessible from main().
2
setMarks() acts as a gatekeeper (Setter). It validates data before saving.
3
getMarks() provides read-only access (Getter).
4
This prevents accidental or malicious data corruption (e.g., setting marks to 150).
5
Encapsulation = Data Hiding + Public Access Methods.
#include <iostream>
using namespace std;
class Student {
private:
    int marks;          // hidden
public:
    void setMarks(int m){
        if(m>=0 && m<=100) marks=m;
        else cout<<"Invalid!"<<endl;
    }
    int getMarks(){ return marks; }
    void display(){ cout<<"Marks: "<<marks<<endl; }
};
int main(){
    Student s;
    s.setMarks(85);   // valid
    s.display();
    s.setMarks(150);  // rejected
    cout<<"Current: "<<s.getMarks()<<endl;
    // s.marks = 90;  // ERROR: private
    return 0;
}
► Expected Output
Marks: 85 Invalid! Current: 85
1
private int marks — completely hidden. Writing s.marks=90 outside the class gives a compile error.
2
setMarks() is a setter with built-in validation. Only valid values (0–100) are accepted.
3
s.setMarks(85) — 85 is valid → stored. marks=85.
4
s.setMarks(150) — 150 > 100 → rejected. marks stays 85. This is data protection.
5
getMarks() is a getter — allows reading but not tampering. Encapsulation = private data + public controlled access.
Common MistakeMaking ALL members public defeats encapsulation. Always make data members private and provide public methods to access them.
#include <iostream>
using namespace std;
class Student { private: int marks; public: void setMarks(int m){ if(m>=0) marks=m; } int getMarks(){ return marks; } };
int main(){ Student s; s.setMarks(90); cout<<s.getMarks(); return 0; }
► Expected Output
90
1
Data is private (hidden).
2
Public methods (getters/setters) provide controlled access.
3
Validation is possible inside setters.
🔨 Build From Scratch — Encapsulation
class Student { private: int m; public: void set(int x){ m=x; } };
► Expected Output
1
Hide data.
2
Controlled access.
Memory LockEncapsulation = Private data + Public methods = Data hiding
Capsule = chemicals hidden inside = data hidden inside class

04

Inheritance

Real-Life AnalogyA child inherits traits from parents — eye color, height. In C++, a child class inherits properties and methods from a parent class. No need to rewrite!

Definition

Inheritance allows a child class (derived) to acquire properties and methods of a parent class (base). It promotes code reuse.

Syntax

class Child : public Parent {
    // inherits all public members of Parent
    // can add its own members
};

Real-Life Examples

Vehicle → Car / Bike

Parent: Vehicle (speed, fuel, display()). Child: Car adds airConditioning(); Bike adds helmet().

BankAccount → SavingsAccount / CurrentAccount

Parent: BankAccount (accountNo, balance). Child: SavingsAccount adds interest; CurrentAccount adds overdraft.

Employee → Manager / Developer

Parent: Employee (name, ID, salary). Child: Manager adds bonus; Developer adds programmingLanguage.

Complete Program

#include <iostream>
using namespace std;

class Vehicle {          // Parent class
public:
    int speed;
    int fuel;
    void setData(int s, int f) { speed = s; fuel = f; }
    void display() {
        cout << "Speed: " << speed << " | Fuel: " << fuel << endl;
    }
};

class Car : public Vehicle {   // Child class
public:
    void carFeature() {
        cout << "Car has Air Conditioning" << endl;
    }
};

class Bike : public Vehicle {  // Another child class
public:
    void bikeFeature() {
        cout << "Bike requires Helmet" << endl;
    }
};

int main() {
    Car c;
    c.setData(120, 40);   // inherited from Vehicle
    c.display();          // inherited from Vehicle
    c.carFeature();       // Car's own method

    Bike b;
    b.setData(80, 15);
    b.display();
    b.bikeFeature();
    return 0;
}
► Expected Output
Speed: 120 | Fuel: 40 Car has Air Conditioning Speed: 80 | Fuel: 15 Bike requires Helmet
1
Car and Bike both inherit speed, fuel, setData(), and display() from Vehicle — no need to rewrite.
2
Each child adds its own specific feature method.
3
: public Vehicle means Car is a Vehicle — it gets all public members of Vehicle.
Exam Answer — 5 marks

Inheritance is an OOP feature that allows a derived (child) class to inherit attributes and methods from a base (parent) class. Syntax: class Child : public Parent { };. It promotes code reuse and establishes an IS-A relationship (Car IS-A Vehicle). Types: Single, Multiple, Multilevel, Hierarchical, Hybrid. Example: Vehicle (base) has speed and display(); Car (derived) inherits these and adds its own features.

#include <iostream>
using namespace std;
class Employee {          // base
public:
    string name; double salary;
    void setData(string n, double s){ name=n; salary=s; }
    void display(){ cout<<"Name: "<<name<<" Salary: "<<salary<<endl; }
};
class Manager : public Employee {  // derived
public:
    double bonus;
    void showTotal(){ cout<<name<<"'s total = "<<salary+bonus<<endl; }
};
int main(){
    Manager m;
    m.setData("Priya", 50000);  // inherited
    m.display();                 // inherited
    m.bonus = 10000;
    m.showTotal();               // Manager's own
    return 0;
}
► Expected Output
Name: Priya Salary: 50000 Priya's total = 60000
1
class Manager : public Employee — the colon means 'inherits from'. Manager gets ALL public members of Employee.
2
m.setData() — defined in Employee, used by Manager. No rewriting needed. This is code reuse.
3
m.display() — also from Employee. Manager didn't define it but can call it.
4
m.bonus and showTotal() — Manager's own additions on top of Employee.
5
Manager IS-A Employee: every Manager has name, salary PLUS bonus. Child extends parent without modifying it.
#include <iostream>
using namespace std;
class Person { public: string name; };
class Student : public Person { public: int roll; };
int main(){ Student s; s.name="Arun"; s.roll=101; cout<<s.name<<" "<<s.roll; return 0; }
► Expected Output
Arun 101
1
Define a base class (Person).
2
Inherit using : syntax.
3
Student now has access to Person's public members.
🔨 Build From Scratch — Inheritance
class A {}; class B : public A {};
► Expected Output
1
Reuse code.
2
IS-A relationship.
Memory LockInheritance = Child class gets parent's properties for FREE
: public Parent = "I am a type of Parent"
No rewriting = Code reuse

05

Polymorphism

Real-Life AnalogyA phone CALL works differently based on who you call — casual with a friend, formal with your boss. Same action (call()), different behavior. That is polymorphism.

Definition

Polymorphism means "many forms". The same method name performs different actions depending on the object that calls it.

Real-Life Examples

Vehicle Example — move()

Car moves on road, Boat moves on water, Plane moves in air. Same method move(), different implementation.

Bank System — calculateInterest()

SavingsAccount → low interest; FixedDeposit → high interest; CurrentAccount → no interest. Same method, different results.

Complete Program

#include <iostream>
using namespace std;

class Person {
public:
    virtual void getRole() {
        cout << "I am a person" << endl;
    }
};

class Teacher : public Person {
public:
    void getRole() {
        cout << "Teacher teaches students" << endl;
    }
};

class Student : public Person {
public:
    void getRole() {
        cout << "Student learns from teacher" << endl;
    }
};

int main() {
    Teacher t;
    Student s;
    t.getRole();   // Teacher's version
    s.getRole();   // Student's version
    return 0;
}
► Expected Output
Teacher teaches students Student learns from teacher
1
virtual keyword in the base class allows the child class to override the method.
2
Both Teacher and Student have getRole() but each prints different output — same method name, different behavior.
Exam Answer — 5 marks

Polymorphism means "many forms". It is the ability of a method to perform different actions based on the object. Achieved using virtual functions. Example: Person has getRole(); Teacher overrides it to print "Teacher teaches", Student overrides it to print "Student learns". Same method name, different behavior per class. Types: Compile-time (function overloading) and Run-time (virtual functions).

#include <iostream>
using namespace std;
class Shape {
public:
    virtual void draw(){ cout<<"Generic shape"<<endl; }
};
class Circle : public Shape {
public:
    void draw(){ cout<<"Drawing Circle O"<<endl; }
};
class Rect : public Shape {
public:
    void draw(){ cout<<"Drawing Rectangle []"<<endl; }
};
int main(){
    Shape* ptr;
    Circle c; Rect r;
    ptr=&c; ptr->draw();  // Circle
    ptr=&r; ptr->draw();  // Rect
    return 0;
}
► Expected Output
Drawing Circle O Drawing Rectangle []
1
virtual void draw() in Shape — tells C++: decide which version to call at RUNTIME based on the actual object.
2
Circle and Rect both override draw() with their own version.
3
Shape* ptr — a base class pointer that can point to any Shape-derived object.
4
ptr=&c; ptr->draw() — ptr points to Circle. Virtual dispatch checks actual type → calls Circle::draw().
5
ptr=&r; ptr->draw() — same pointer, now points to Rect → calls Rect::draw(). Same call, different behaviour = polymorphism.
#include <iostream>
using namespace std;
class Shape { public: virtual void draw(){ cout<<"Shape"; } };
class Circle : public Shape { public: void draw(){ cout<<"Circle"; } };
int main(){ Shape *s; Circle c; s=&c; s->draw(); return 0; }
► Expected Output
Circle
1
Use virtual in base class.
2
Override in derived class.
3
Base pointer calling derived method at runtime.
🔨 Build From Scratch — Polymorphism
class S { virtual void d(); };
► Expected Output
1
Many forms.
2
Dynamic binding.
Memory LockPoly = Many | Morphism = Forms | Same method, different behavior
virtual keyword = "child can override this"

06

Abstraction

Real-Life AnalogyTV Remote — you press Power, Volume, Channel. You don't know how the signals work internally. Abstraction = show WHAT to do, hide HOW it works.

Definition

Abstraction means showing only essential features and hiding internal implementation details. In C++, this is achieved using abstract classes with pure virtual functions (= 0).

Real-Life Examples

ATM Machine

You see: Insert card, Enter PIN, Withdraw cash. Hidden: Bank server communication, money counting, verification logic.

Car Driving

You use: Steering, Accelerator, Brake. Hidden: How engine burns fuel, how gears work, how brakes stop the car.

Complete Program

#include <iostream>
using namespace std;

class Remote {         // Abstract class
public:
    virtual void pressButton() = 0;   // pure virtual = must override
};

class TV : public Remote {
public:
    void pressButton() {
        cout << "TV is turned ON" << endl;
    }
};

class AC : public Remote {
public:
    void pressButton() {
        cout << "AC is set to 22 degrees" << endl;
    }
};

int main() {
    TV myTV;
    AC myAC;
    myTV.pressButton();
    myAC.pressButton();
    return 0;
}
► Expected Output
TV is turned ON AC is set to 22 degrees
1
Remote is an abstract class — it has a pure virtual function (= 0). Cannot be instantiated directly.
2
TV and AC each provide their own implementation of pressButton(). The user only calls the button — doesn't know how it works internally.
Common MistakeCannot create an object of an abstract class directly. Remote r; gives compile error. Only derived classes that override all pure virtual functions can be instantiated.
Exam Answer — 5 marks

Abstraction is the OOP concept of hiding implementation details and showing only necessary features. Achieved in C++ using abstract classes with pure virtual functions (= 0). Example: Remote is an abstract class with pure virtual pressButton(). TV and AC inherit it and provide their specific implementations. The user only sees what the button does, not how it works. Benefits: Reduces complexity, improves security, enables clean interface design.

#include <iostream>
using namespace std;
class Vehicle {             // abstract class
public:
    virtual void start() = 0;  // pure virtual
    virtual void stop()  = 0;
};
class Car : public Vehicle {
public:
    void start(){ cout<<"Car: vroom!"<<endl; }
    void stop() { cout<<"Car: stopped."<<endl; }
};
class Boat : public Vehicle {
public:
    void start(){ cout<<"Boat: splash!"<<endl; }
    void stop() { cout<<"Boat: anchored."<<endl; }
};
int main(){
    // Vehicle v; // ERROR: abstract!
    Car car; Boat boat;
    car.start(); car.stop();
    boat.start(); boat.stop();
    return 0;
}
► Expected Output
Car: vroom! Car: stopped. Boat: splash! Boat: anchored.
1
virtual void start() = 0 — pure virtual. The = 0 makes Vehicle abstract. It defines WHAT to do, not HOW.
2
Any class that inherits Vehicle MUST override all pure virtuals, or it also becomes abstract.
3
Vehicle v; would cause a compile error — you cannot instantiate an abstract class.
4
Car and Boat each provide their own start() and stop() implementations.
5
The user calls car.start() without knowing the engine internals. That hidden complexity IS abstraction.
#include <iostream>
using namespace std;
class Vehicle { public: virtual void start()=0; };
class Car : public Vehicle { public: void start(){ cout<<"Car started"; } };
int main(){ Car c; c.start(); return 0; }
► Expected Output
Car started
1
Pure virtual function (=0) makes class abstract.
2
Cannot create object of abstract class.
3
Derived class must implement the pure virtual method.
🔨 Build From Scratch — Abstraction
class V { virtual void s()=0; };
► Expected Output
1
Hide complexity.
2
Interface only.
Memory LockAbstraction = Hide HOW, Show WHAT
Abstract class + pure virtual (= 0) = abstraction in C++
Cannot create object of abstract class directly

07

Classes and Objects in C++

Real-Life AnalogyA class is like a cookie cutter (blueprint). An object is the actual cookie made from it. You can make many different cookies from the same cutter.

Class Syntax

class ClassName {
private:
    // hidden data members
public:
    // accessible methods
};

Key Points

Data Members (Attributes)

Variables defined inside a class that store the object's data. Example: string name; int marks;

Member Functions (Methods)

Functions defined inside a class that define the object's behavior. Example: setData(), displayData()

Creating Objects

Syntax: ClassName objectName; or ClassName obj1, obj2;. Each object gets its own copy of data members.

Accessing Members

Use dot operator: obj.method() or obj.variable (if public).

Complete Program

#include <iostream>
using namespace std;

class Student {
private:
    string name;
    int marks;

public:
    void setData(string n, int m) {
        name = n;
        marks = m;
    }
    void displayData() {
        cout << "Name: " << name << endl;
        cout << "Marks: " << marks << endl;
    }
};

int main() {
    Student s1, s2;       // two separate objects

    s1.setData("Arun", 85);
    s2.setData("Priya", 92);

    cout << "Student 1:" << endl;
    s1.displayData();
    cout << "Student 2:" << endl;
    s2.displayData();
    return 0;
}
► Expected Output
Student 1: Name: Arun Marks: 85 Student 2: Name: Priya Marks: 92
1
Class Student defines the blueprint — it has name, marks, setData(), displayData().
2
s1 and s2 are two separate objects — each has its own copy of name and marks.
3
s1.setData("Arun", 85) stores "Arun" and 85 in s1's private data. s2 is unaffected.
Exam Answer — 5 marks

A class is a user-defined blueprint that groups data (attributes) and functions (methods) together. An object is an instance of a class — a real entity created from the blueprint. Syntax: ClassName obj;. Each object has its own copy of data members. Members are accessed using the dot operator (obj.method()). Access specifiers (private, public, protected) control visibility. Example: Student class with private name/marks and public setData()/displayData().

#include <iostream>
using namespace std;
class Rectangle {
private:
    double width, height;
public:
    void setDimensions(double w, double h){ width=w; height=h; }
    double area()    { return width * height; }
    double perimeter(){ return 2*(width+height); }
    void display(){
        cout<<"Width: "<<width<<" Height: "<<height<<endl;
        cout<<"Area: "<<area()<<" Perimeter: "<<perimeter()<<endl;
    }
};
int main(){
    Rectangle r1, r2;
    r1.setDimensions(5, 3);
    r2.setDimensions(10, 4);
    cout<<"Rectangle 1:"<<endl; r1.display();
    cout<<"Rectangle 2:"<<endl; r2.display();
    return 0;
}
► Expected Output
Rectangle 1: Width: 5 Height: 3 Area: 15 Perimeter: 16 Rectangle 2: Width: 10 Height: 4 Area: 40 Perimeter: 28
1
private double width, height — data is hidden. Cannot access r1.width directly from main().
2
setDimensions() is the setter. Both r1 and r2 call it with different values — each stores independently.
3
area() and perimeter() compute from the object's own private data.
4
display() calls area() and perimeter() internally — member functions can call other member functions.
5
r1 and r2 are separate objects — r1's width=5, r2's width=10. Each lives in its own memory location.
#include <iostream>
using namespace std;
class Rectangle { public: int l,b; int area(){ return l*b; } };
int main(){ Rectangle r; r.l=10; r.b=5; cout<<r.area(); return 0; }
► Expected Output
50
1
Data members (l,b) and member function (area).
2
Object r takes memory in stack.
3
Calling member function for specific data instance.
Memory LockClass = blueprint (cookie cutter) | Object = instance (cookie)
Dot operator (.) = access object members
private = hidden | public = accessible

08

Access Specifiers

Real-Life AnalogyIn a hospital: Public area = anyone enters. Private area = staff only. Protected area = staff + authorized visitors. Access specifiers work the same way for class members.

Definition

Access specifiers control where class members can be accessed. They implement data hiding and encapsulation.

1. public

Members are accessible anywhere — inside the class, outside, and in derived classes. Used for methods the user needs to call.

class Sample { public: int x; };

2. private

Members accessible only within the same class. Default for class members. Used to protect data.

class Sample { private: int y; };

3. protected

Members accessible within the class and derived (child) classes. Not accessible outside.

class Sample { protected: int z; };

Comparison Table

Access Specifier Within Class Outside Class Derived Class
public Yes Yes Yes
private Yes No No
protected Yes No Yes

Complete Program

#include <iostream>
using namespace std;

class Student {
private:
    int marks;       // only class can access
protected:
    int rollNo;      // class + child classes
public:
    void setData() {
        marks = 85;
        rollNo = 101;
    }
    void display() {
        cout << "Marks: " << marks << endl;
        cout << "Roll No: " << rollNo << endl;
    }
};

int main() {
    Student s;
    s.setData();
    s.display();
    // s.marks = 90;   // ERROR: private
    // s.rollNo = 102; // ERROR: protected
    return 0;
}
► Expected Output
Marks: 85 Roll No: 101
Common Exam TrapDefault access in a class is private. Default access in a struct is public. Know this difference!
#include <iostream>
using namespace std;
class Person {
private:
    int age;           // class only
protected:
    string name;       // class + children
public:
    void setData(string n, int a){ name=n; age=a; }
    void display(){ cout<<"Name: "<<name<<" Age: "<<age<<endl; }
};
class Student : public Person {
public:
    void greet(){
        cout<<"Hi, I am "<<name<<endl;  // protected: OK
        // cout<<age;  // private: ERROR
    }
};
int main(){
    Person p; p.setData("Alice",20); p.display();
    Student s; s.setData("Bob",18);
    s.display(); s.greet();
    // p.age = 30;   // ERROR: private
    // s.name = "X"; // ERROR: protected, not outside
    return 0;
}
► Expected Output
Name: Alice Age: 20 Name: Bob Age: 18 Hi, I am Bob
1
private int age — only Person's own methods can read/write age. Even Student (child) cannot access it.
2
protected string name — Person + Student can access it. Outside main() cannot.
3
public setData()/display() — accessible everywhere. These are the safe entry points.
4
In Student::greet(), name is accessible (protected), but age would cause a compile error (private).
5
In main(), p.age=30 and s.name="X" both give errors — private and protected block outside access.
#include <iostream>
using namespace std;
class Test { private: int a; protected: int b; public: int c; };
int main(){ Test t; t.c=10; /* t.a=5; t.b=6; ERROR */ return 0; }
► Expected Output
(Compilation only)
1
Private: Only inside class.
2
Protected: Class + Derived.
3
Public: Accessible everywhere.
Memory Lockpublic = open to all | private = class only | protected = class + children
Default in class = private | Default in struct = public

09

Methods — Constructors, Static & Inline

Regular Methods — Inside vs Outside Class

Inside Class Method

class Sample {
public:
    void show() { cout << "Inside"; }   // defined directly
};

Outside Class Method (using :: operator)

class Sample {
public:
    void show();   // declaration only
};
void Sample::show() {  // :: = scope resolution
    cout << "Outside";
}

Constructor Method

A constructor is a special method that is automatically called when an object is created. It initializes data members.

Rules of Constructor

✓ Name is same as class name  ✓ No return type  ✓ Called automatically on object creation

Static Method

A static method belongs to the class itself, not to any specific object. Called using the class name, not object. Can only access static data members.

Inline Method

An inline method is expanded at the point of call (no function call overhead). Suitable for short, frequently called methods. Uses keyword inline.

Complete Program — All Three Types

#include <iostream>
using namespace std;

class Student {
    int id;
public:
    static string college;   // static data member

    Student(int i) {          // Constructor
        id = i;
        cout << "Student created with ID: " << id << endl;
    }

    inline void showId() {   // Inline method
        cout << "Student ID: " << id << endl;
    }

    static void showCollege() {  // Static method
        cout << "College: " << college << endl;
    }
};

string Student::college = "SRM University";  // static init

int main() {
    Student s1(101);    // constructor called automatically
    Student s2(102);
    s1.showId();
    s2.showId();
    Student::showCollege();  // called on class, not object
    return 0;
}
► Expected Output
Student created with ID: 101 Student created with ID: 102 Student ID: 101 Student ID: 102 College: SRM University
1
Constructor Student(int i) runs automatically when s1 and s2 are created — no need to call it manually.
2
showId() is inline — compiler replaces the call with the function body directly for speed.
3
showCollege() is static — called with Student::showCollege(), not through an object. Same college for all students.
Exam Answer — 5 marks

Constructor: Special method with class name, no return type, auto-called on object creation. Initializes data. Static method: Belongs to the class, not object. Called using ClassName::method(). Accesses only static members. Inline method: Uses inline keyword. Function body is pasted at call site — reduces overhead for small functions. All three demonstrated in Student class above.

#include <iostream>
using namespace std;
class Counter {
    int count;
public:
    static int total;        // shared across all objects

    Counter(){ count=0; total++; cout<<"Object "<<total<<" created"<<endl; }

    inline void increment(){ count++; }   // inline: fast, small

    void display(){ cout<<"Count: "<<count<<endl; }

    static void showTotal(){ cout<<"Total objects: "<<total<<endl; }
};
int Counter::total = 0;   // define static outside

int main(){
    Counter c1, c2;
    c1.increment(); c1.increment();
    c2.increment();
    c1.display(); c2.display();
    Counter::showTotal();
    return 0;
}
► Expected Output
Object 1 created Object 2 created Count: 2 Count: 1 Total objects: 2
1
Constructor Counter(): auto-called when c1 and c2 are created. Initializes count=0 and increments shared total.
2
static int total: ONE shared variable for ALL Counter objects. c1 and c2 share the same total.
3
int Counter::total = 0: static members must be defined outside the class (just once).
4
inline increment(): compiler pastes the body directly at each call site — no function call overhead. Good for tiny, frequent methods.
5
Counter::showTotal(): called on the CLASS, not an object. Static methods can only access static data.
#include <iostream>
using namespace std;
class Box { public: inline int sq(int s){ return s*s; } static int count; Box(){ count++; } };
int Box::count=0;
int main(){ Box b1, b2; cout<<Box::count; return 0; }
► Expected Output
2
1
Inline suggests compiler to replace call with code.
2
Static variable shared by all objects.
3
Static accessed via Class::Name.
Memory LockConstructor = same name as class, no return type, auto-called
Static = belongs to class (::), not object
Inline = fast, body pasted at call point

10

I/O Operations in C++

Real-Life Analogycout is like speaking to someone (output). cin is like listening to someone (input). The stream flows from keyboard to program (cin) and from program to screen (cout).

Key Objects

Object Purpose Operator
cin Standard input (keyboard) >> extraction
cout Standard output (monitor) << insertion
cerr Error output <<
endl New line + flush buffer

Types of I/O

Console I/O

Uses cin and cout for keyboard/screen interaction. Most common in programs.

File I/O

Uses ifstream, ofstream, fstream to read/write files.

Formatted I/O

Uses manipulators like setw, setprecision to control output format.

Complete Program

#include <iostream>
using namespace std;

int main() {
    int age;
    string name;

    cout << "Enter your name: ";
    cin >> name;
    cout << "Enter your age: ";
    cin >> age;

    cout << "Name: " << name << endl;
    cout << "Age: " << age << endl;
    return 0;
}
► Sample Output (if input is: Alice 20)
Enter your name: Alice Enter your age: 20 Name: Alice Age: 20
Tip<< (insertion) goes INTO cout — think "putting data INTO the stream". >> (extraction) comes OUT of cin — think "pulling data OUT of the stream".
#include <iostream>
#include <string>
using namespace std;
int main(){
    string name;
    int rollNo, marks;

    cout<<"Enter Roll No: "; cin>>rollNo;
    cout<<"Enter Name: ";    cin>>name;
    cout<<"Enter Marks: ";   cin>>marks;

    cout<<"--- Student Report ---"<<endl;
    cout<<"Roll No : "<<rollNo<<endl;
    cout<<"Name    : "<<name<<endl;
    cout<<"Marks   : "<<marks<<endl;

    if(marks >= 50) cout<<"Result  : PASS"<<endl;
    else             cout<<"Result  : FAIL"<<endl;
    return 0;
}
► Expected Output
Enter Roll No: 101 Enter Name: Arun Enter Marks: 78 --- Student Report --- Roll No : 101 Name : Arun Marks : 78 Result : PASS
1
cout << "Enter Roll No: " — insertion operator sends text to screen. No newline until endl.
2
cin >> rollNo — extraction operator waits for keyboard input and stores it in rollNo.
3
cin >> name — reads one word (stops at space). For full name with spaces use getline(cin, name).
4
cout << rollNo << endl — chain multiple values with <<. endl flushes and moves to new line.
5
The if-else uses marks to decide PASS/FAIL. This is basic console I/O with decision logic combined.
#include <iostream>
using namespace std;
int main(){ int n; cout<<"Enter n: "; cin>>n; cout<<"Value is "<<n; return 0; }
► Expected Output
Enter n: 5 Value is 5
1
cout for output.
2
cin for input.
3
Chain with << and>>.
Memory Lockcin >> = input (keyboard reads into variable)
cout << = output (variable prints to screen)
Header: #include <iostream> always required

11

Data Types, Variables & Type Conversion

Data Types in C++

Type Example Size Range
int int age = 20; 4 bytes -2B to 2B
float float pi = 3.14; 4 bytes 6 decimal digits
double double x = 3.14159; 8 bytes 15 decimal digits
char char c = 'A'; 1 byte 0 to 255
bool bool pass = true; 1 byte true/false
string string name = "Ali"; varies any text

Variables

A variable is a named memory location to store data. Syntax: data_type variable_name; or with init: int age = 20;

Rules for Variable Names

Must begin with a letter or underscore | No spaces | No keywords | Case-sensitive (age ≠ Age)

static vs const

Feature static const
Purpose Retains value between calls Prevents modification
Value change Allowed Not allowed
Memory Single shared location Normal allocation
Lifetime Entire program Depends on scope
#include <iostream>
using namespace std;
void counter() {
    static int count = 0;   // retains value
    const int MAX = 10;      // cannot change
    count++;
    cout << "Count: " << count << " | MAX: " << MAX << endl;
}
int main() {
    counter(); counter(); counter();
    return 0;
}
► Expected Output
Count: 1 | MAX: 10 Count: 2 | MAX: 10 Count: 3 | MAX: 10

Type Conversion

1. Implicit (Automatic)

Compiler converts smaller type to larger automatically.

int a = 10;
float b = a;   // int auto-converts to float
cout << b;     // Output: 10

2. Explicit (Type Casting)

Programmer manually converts using (type) syntax.

float x = 9.8;
int y = (int)x;  // explicit cast, drops decimal
cout << y;        // Output: 9
#include <iostream>
using namespace std;
int main(){
    int    age    = 20;
    float  height = 5.9f;
    double pi     = 3.14159265;
    char   grade  = 'A';
    bool   pass   = true;
    string name   = "Arun";

    cout<<"int    age    = "<<age<<endl;
    cout<<"float  height = "<<height<<endl;
    cout<<"double pi     = "<<pi<<endl;
    cout<<"char   grade  = "<<grade<<endl;
    cout<<"bool   pass   = "<<pass<<endl;
    cout<<"string name   = "<<name<<endl;

    // Type conversion
    float x = 9.8f;
    int   y = (int)x;   // explicit cast: drops decimal
    cout<<"Cast 9.8 to int: "<<y<<endl;
    return 0;
}
► Expected Output
int age = 20 float height = 5.9 double pi = 3.14159 char grade = A bool pass = 1 string name = Arun Cast 9.8 to int: 9
1
int age=20 — 4 bytes, whole numbers only. Range: -2 billion to +2 billion.
2
float height=5.9f — 4 bytes, 6 decimal digits. The 'f' suffix marks it as float literal.
3
double pi=3.14159265 — 8 bytes, 15 decimal digits. More precise than float.
4
char grade='A' — 1 byte, stores a single character. Single quotes for char, double for string.
5
bool pass=true — cout prints 1 for true, 0 for false.
6
(int)x — explicit cast. Truncates the decimal part. 9.8 becomes 9, NOT rounded.
#include <iostream>
using namespace std;
int main(){ int i=10; float f=1.1; char c='A'; bool b=true; return 0; }
► Expected Output
1
Primitive types: int, float, char, bool.
2
Type modifiers: long, short, signed, unsigned.
3
Boolean prints as 1/0.
Memory Lockstatic = remembers value | const = cannot change
Implicit = auto (int to float) | Explicit = manual (float to int)

12

Control Statements, Loops & Arrays

Conditional Statements

Statement Use
if Execute block if condition is true
if-else One block if true, another if false
else-if ladder Check multiple conditions
switch Select one from many specific values
#include <iostream>
using namespace std;
int main() {
    int marks = 85;
    if (marks >= 90)      cout << "Grade A";
    else if (marks >= 75) cout << "Grade B";
    else                   cout << "Grade C";

    int day = 3;
    switch (day) {
        case 1: cout << " Monday"; break;
        case 2: cout << " Tuesday"; break;
        case 3: cout << " Wednesday"; break;
        default: cout << " Invalid";
    }
    return 0;
}
► Expected Output
Grade B Wednesday

Loops

Loop Use When Entry Check
for Number of iterations known Yes
while Iterations unknown, condition-based Yes
do-while Must execute at least once No (exit check)
#include <iostream>
using namespace std;
int main() {
    // for loop
    for (int i = 1; i <= 3; i++) cout << i << " ";
    cout << endl;

    // while loop
    int j = 1;
    while (j <= 3) { cout << j << " "; j++; }
    cout << endl;

    // do-while (runs once even if false)
    int k = 6;
    do { cout << k; } while (k <= 5);
    return 0;
}
► Expected Output
1 2 3 1 2 3 6

Arrays

An array stores multiple values of the same type in contiguous memory. Index starts at 0.

#include <iostream>
using namespace std;
int main() {
    int marks[5] = {80, 75, 90, 85, 70};
    for (int i = 0; i < 5; i++) {
        cout << "Student " << i+1 << ": " << marks[i] << endl;
    }
    return 0;
}
► Expected Output
Student 1: 80 Student 2: 75 Student 3: 90 Student 4: 85 Student 5: 70
Common MistakeArray index starts at 0 — an array of size 5 has valid indices 0,1,2,3,4. Accessing index 5 is out-of-bounds (undefined behavior).
#include <iostream>
using namespace std;
int main(){
    int marks[5] = {72, 88, 45, 91, 60};
    int sum = 0;

    for(int i=0; i<5; i++){
        sum += marks[i];
        string grade;
        if(marks[i] >= 90)      grade = "A";
        else if(marks[i] >= 75) grade = "B";
        else if(marks[i] >= 50) grade = "C";
        else                     grade = "F";
        cout<<"Subject "<<i+1<<": "<<marks[i]<<" Grade: "<<grade<<endl;
    }

    double avg = (double)sum / 5;
    cout<<"Average: "<<avg<<endl;
    return 0;
}
► Expected Output
Subject 1: 72 Grade: C Subject 2: 88 Grade: B Subject 3: 45 Grade: F Subject 4: 91 Grade: A Subject 5: 60 Grade: C Average: 71.2
1
int marks[5]={...} — array of 5 integers. Index 0–4. Stored contiguously in memory.
2
for(int i=0; i<5; i++) — runs exactly 5 times. i goes 0,1,2,3,4 matching array indices.
3
sum += marks[i] — accumulates total each iteration.
4
if-else ladder checks marks in descending order. First matching condition wins — order matters.
5
(double)sum/5 — explicit cast ensures decimal division. Without cast: 356/5=71 (integer division loses .2).
#include <iostream>
using namespace std;
int main(){ int a[]={1,2,3,4,5}, sum=0; for(int i=0;i<5;i++) sum+=a[i]; cout<<sum; return 0; }
► Expected Output
15
1
Initialize array.
2
For loop for iteration.
3
Accumulate sum.
Memory Lockfor = known count | while = condition-based | do-while = at least once
Array index starts at 0 | Size = n, last index = n-1
#include <iostream>
using namespace std;

/*  UML Class Diagram:
    +-----------------------+
    |       Student         |
    +-----------------------+
    | - rollNo : int        |
    | - name   : string     |
    | - marks  : float      |
    +-----------------------+
    | + setData()  : void   |
    | + display()  : void   |
    | + getGrade() : string |
    +-----------------------+
*/

class Student {
private:
    int rollNo; string name; float marks;
public:
    void setData(int r, string n, float m){ rollNo=r; name=n; marks=m; }
    string getGrade(){
        if(marks>=90) return "A";
        if(marks>=75) return "B";
        if(marks>=50) return "C";
        return "F";
    }
    void display(){
        cout<<"Roll: "<<rollNo<<" Name: "<<name<<" Marks: "<<marks<<" Grade: "<<getGrade()<<endl;
    }
};

int main(){
    Student s1, s2;
    s1.setData(101,"Arun",88.5);
    s2.setData(102,"Priya",92.0);
    s1.display(); s2.display();
    return 0;
}
► Expected Output
Roll: 101 Name: Arun Marks: 88.5 Grade: B Roll: 102 Name: Priya Marks: 92 Grade: A
1
The UML diagram in the comment is the OOD blueprint. - means private, + means public.
2
Three private attributes map to private: int rollNo; string name; float marks;
3
Three public methods map to public: setData(), getGrade(), display()
4
getGrade() returns a string based on marks — notice member functions can call other member functions.
5
UML → Code translation: draw the diagram first (OOAD), then convert each box to a C++ class. This is the exam workflow.

13

UML Diagrams

Real-Life AnalogyBefore building a house, you draw a floor plan. UML is the "floor plan" for software — it shows classes, relationships, and interactions visually before coding.

What is UML?

UML (Unified Modeling Language) is a standard visual language to design, visualize, and document software systems. Used in OOAD before coding begins.

1. Class Diagram (Most Important)

Structure

-------------------------
|      ClassName        |
|------------------------|
| - attribute1 : type   |
| - attribute2 : type   |
|------------------------|
| + method1() : void    |
| + method2() : type    |
-------------------------

Symbols

+ = public   - = private   # = protected

UML Class Diagram → Code

#include <iostream>
using namespace std;

class Student {               // UML: | Student |
private:
    int rollNo;               // - rollNo : int
    string name;              // - name : string
public:
    void setData(int r, string n) {  // + setData()
        rollNo = r; name = n;
    }
    void display() {          // + display()
        cout << "Roll: " << rollNo << " Name: " << name << endl;
    }
};

int main() {
    Student s1;
    s1.setData(101, "Arun");
    s1.display();
    return 0;
}
► Expected Output
Roll: 101 Name: Arun

2. Use Case Diagram

Shows what the system does from the user's point of view. Key elements:

Actor = user/external system  |  Use Case = system functionality  |  System Boundary = scope

Example — ATM System

Actor: Customer → Use Cases: Withdraw Cash, Check Balance, Deposit Money

3. Sequence Diagram

Shows how objects interact in time order. Key elements: Objects, Lifelines (dashed lines), Messages (arrows).

Example — Login Process

User → LoginPage: enterCredentials() → AuthServer: verifyUser() → Database: checkData() → Response back

4. Activity Diagram

Represents workflow/flow of control — like a flowchart. Elements: Start(●), Action states, Decision(diamond), End(◎).

Example — Online Shopping

Start → Select Product → Add to Cart → Make Payment → Order Confirmed → End

Comparison Table

Diagram Shows When Used
Class Diagram Classes, attributes, methods, relationships System structure design
Use Case Diagram System functionality from user view Requirements phase
Sequence Diagram Object interactions over time Interaction design
Activity Diagram Step-by-step workflow Business logic design
Exam Answer — 5 marks

UML (Unified Modeling Language) is a standard visual language for designing OO systems. Class Diagram: shows classes with + (public), - (private), # (protected) attributes and methods, and relationships like inheritance (arrow). Use Case Diagram: shows actors and system functions. Sequence Diagram: shows time-ordered object interactions. Activity Diagram: shows step-by-step workflows. UML helps plan software before coding, reducing errors and improving communication.

class Student { private: int id; string name; public: void setData(); void getData(); };
► Expected Output
(Structure only)
1
- sign in UML means private.
2
+ sign in UML means public.
3
Class name at top, attributes middle, methods bottom.
Memory LockClass Diagram = structure (+/-/# notation)
Use Case = WHO does WHAT | Sequence = WHO talks to WHOM when
Activity = STEP BY STEP flow

Unit 1 — Final Quick Revision (click each to reveal answer)

Q: What is the difference between OOA and OOD?
OOA = WHAT the system does (analysis/requirements). OOD = HOW the system will be built (design/blueprint).
Q: What are the 4 pillars of OOP?
Encapsulation, Inheritance, Polymorphism, Abstraction (EIPA).
Q: What is encapsulation?
Binding data and methods in a class + making data private + accessing via public methods = data hiding.
Q: What keyword makes inheritance work in C++?
The colon : and access specifier. Syntax: class Child : public Parent { };
Q: What is the purpose of the virtual keyword?
Allows child classes to override parent methods (runtime polymorphism).
Q: What is a pure virtual function?
A function declared as = 0. Makes the class abstract. Child must override it. Enables abstraction.
Q: What is the default access specifier in a class?
private. (In struct it is public.)
Q: What are the rules for a constructor?
Same name as class, no return type, called automatically when object is created.
Q: How do you call a static method?
ClassName::methodName() — using the class name and scope resolution operator, not via an object.
Q: What does endl do?
Moves cursor to new line AND flushes the output buffer. Equivalent to '\n' + flush.
T1

Mini Test 1 — OOAD & OOP (5 min)

Answer without looking above (click to reveal)

1. What does OOAD stand for? Name its two phases.
Object-Oriented Analysis and Design. Phase 1: OOA (what the system does). Phase 2: OOD (how to build it).
2. List the 4 pillars of OOP with one line each.
Encapsulation=hide data. Inheritance=reuse parent. Polymorphism=same method different behavior. Abstraction=hide how, show what.
3. Predict output: class A { public: int x=5; }; int main(){ A obj; cout<<obj.x++<<" "<<obj.x; }
5 6 — post-increment prints 5 first, then x becomes 6.
4. True/False: A class is an instance of an object.
FALSE. An object is an instance of a class. Class = blueprint, Object = actual entity.
5. Write syntax to create two objects s1,s2 of class Student.
Student s1, s2; (or) Student s1; Student s2;
P1

Practice — OOAD & OOP

🟢 Basic

💻 Coding Q1 — Basic

Create a class Book with public members: title (string), price (float). In main, create an object, assign values, and print them.

#include<iostream>
using namespace std;
class Book{
public:
    string title;
    float price;
};
int main(){
    Book b;
    b.title="C++ Basics";
    b.price=250.0;
    cout<<b.title<<" - Rs."<<b.price;
    return 0;
}
Output
C++ Basics - Rs.250
💻 Coding Q2 — Basic

Create class Circle with radius (int). Add method area() that prints area = 3.14 * r * r.

#include<iostream>
using namespace std;
class Circle{
public:
    int radius;
    void area(){ cout<<"Area="<<3.14*radius*radius; }
};
int main(){
    Circle c; c.radius=5; c.area();
    return 0;
}
Output
Area=78.5

🟡 Output Trap

⚠ Predict the Output
class A{
public:
    int x=10;
    void show(){ cout<<++x<<" "<<x++<<" "<<x; }
};
int main(){ A obj; obj.show(); }

Output: 11 11 12
++x pre-increments to 11 and prints 11. x++ prints 11 (current value) then increments to 12. Final x is 12.

🔴 Concept Question

✍ Exam Concept

Q: What is the IS-A relationship? Give one example in C++.

IS-A = Inheritance relationship. A derived class IS-A type of base class. Example: Car IS-A Vehicle. Syntax: class Car : public Vehicle { }; — Car inherits all public members of Vehicle.

⚠ Common Mistakes

Mistake 1Forgetting semicolon after class closing brace: class A { }; — the ; after } is MANDATORY.
Mistake 2Trying to access private members from outside: obj.privateVar = 5; — compile error. Use public setter methods.
Mistake 3Confusing class and object: "Class is an object" is WRONG. Class is a blueprint; object is an instance.
Write-From-Scratch Guide — Class + Object in Exam
Step 1: Write #include <iostream> and using namespace std;
Step 2: Write class ClassName {
Step 3: Add private: data members
Step 4: Add public: methods
Step 5: Close with }; (semicolon!)
Step 6: In main(): create object, call methods
T2

Mini Test 2 — Encapsulation, Inheritance & Polymorphism

No peeking — click to reveal

1. Can you access a private data member from outside the class directly?
NO. Private members are accessible only within the same class. Accessing them outside causes a compile error.
2. What is the output? class A{ public: void f(){ cout<<"A"; } }; class B:public A{ public: void f(){ cout<<"B"; } }; int main(){ B obj; obj.f(); }
B — obj is of type B, so B's version of f() is called (method overriding).
3. What keyword enables runtime polymorphism in C++?
virtual — used in the base class method declaration.
4. What is the syntax for inheritance?
class Child : public Parent { };
5. What access specifier is default in a class?
private — all members without specifier are private in a class (but public in a struct).
P2

Practice — Encapsulation, Inheritance & Polymorphism

🟢 Basic — Encapsulation

💻 Coding Q1

Create a class Employee with private salary (double). Add public methods setSalary(double) and getSalary(). In main, set salary to 50000 and print it.

#include<iostream>
using namespace std;
class Employee{
private: double salary;
public:
    void setSalary(double s){ salary=s; }
    double getSalary(){ return salary; }
};
int main(){
    Employee e;
    e.setSalary(50000);
    cout<<"Salary: "<<e.getSalary();
    return 0;
}
Output
Salary: 50000

🟡 Medium — Inheritance

💻 Coding Q2 — Exam Level

Create base class Animal with method speak() printing "Animal speaks". Derive Dog and Cat — override speak() to print "Dog barks" and "Cat meows". Call all three in main.

#include<iostream>
using namespace std;
class Animal{
public:
    virtual void speak(){ cout<<"Animal speaks"<<endl; }
};
class Dog:public Animal{
public:
    void speak(){ cout<<"Dog barks"<<endl; }
};
class Cat:public Animal{
public:
    void speak(){ cout<<"Cat meows"<<endl; }
};
int main(){
    Animal a; Dog d; Cat c;
    a.speak(); d.speak(); c.speak();
    return 0;
}
Output
Animal speaks Dog barks Cat meows

🔴 Output Trap — Polymorphism

⚠ What is the output?
class Base{
public:
    void show(){ cout<<"Base"<<endl; }
};
class Derived:public Base{
public:
    void show(){ cout<<"Derived"<<endl; }
};
int main(){
    Base* p = new Derived();
    p->show();
}

Output: Base
Because show() is NOT virtual in Base. Without virtual, the pointer type (Base*) determines which method is called — not the actual object type. Add virtual to Base::show() to get "Derived".

⚠ Common Mistakes — Inheritance & Polymorphism

Mistake 1Forgetting virtual in base class — without it, polymorphism does NOT work through pointers/references.
Mistake 2Forgetting public in inheritance: class Child : Parent defaults to private inheritance — derived class loses access to base members.
Mistake 3Trying to instantiate an abstract class: Abstract a; — compile error. Abstract classes (with pure virtual) cannot be instantiated.
Write-From-Scratch — Inheritance in Exam
1. Write base class with methods (mark virtual if polymorphism needed)
2. Write: class Child : public Base {
3. Override needed methods inside Child
4. In main: create objects of BOTH base and child
5. Call methods using objects
T3

Mini Test 3 — Access Specifiers, Methods & I/O

Rapid Fire — click to reveal

1. What does :: mean in void Student::show()?
Scope resolution operator — it means show() is defined outside the class but belongs to the Student class.
2. What is wrong? class A{ int x; public: A(){ x=5; } }; int main(){ A obj; cout<<obj.x; }
Error: x is private (default in class). Cannot access obj.x from outside. Need a public getter method.
3. What is the output? int main(){ int a=5; cout<<a++<<" "<<++a; }
5 7 — a++ prints 5 (post), then increments to 6. ++a pre-increments to 7, prints 7.
4. How do you call a static method show() of class A?
A::show(); — using class name and scope resolution, not via object.
5. Which header is needed for cin and cout?
#include <iostream>
P3

Practice — Access Specifiers, Methods & I/O

🟢 Basic

💻 Coding Q1 — Outside Class Method

Define class Rectangle with private length and width. Declare setData() and area() inside class. Define both methods OUTSIDE the class using ::. Print area in main.

#include<iostream>
using namespace std;
class Rectangle{
private:
    int length, width;
public:
    void setData(int l, int w);
    void area();
};
void Rectangle::setData(int l, int w){ length=l; width=w; }
void Rectangle::area(){ cout<<"Area="<<length*width; }
int main(){
    Rectangle r;
    r.setData(5,3);
    r.area();
    return 0;
}
Output
Area=15
💻 Coding Q2 — Constructor + Static

Create class Counter with static member count. Constructor increments count. Static method getCount() returns it. Create 3 objects and print final count.

#include<iostream>
using namespace std;
class Counter{
public:
    static int count;
    Counter(){ count++; }
    static int getCount(){ return count; }
};
int Counter::count=0;
int main(){
    Counter a,b,c;
    cout<<"Objects created: "<<Counter::getCount();
    return 0;
}
Output
Objects created: 3

🟡 Output Trap — I/O + Operators

⚠ Predict Output
int main(){
    int a=3, b=4;
    cout<<a++<<" "<<++b<<" "<<a<<" "<<b;
}

Output: 3 5 4 5
a++ prints 3 (post, then a=4). ++b increments b to 5, prints 5. a is now 4. b is 5.

⚠ Common Mistakes — Methods & I/O

Mistake 1Defining method outside without ::: writing void show() instead of void ClassName::show() makes it a global function, not a class method.
Mistake 2Calling static method via object: obj.showCount() works but is bad practice. Always use ClassName::methodName().
Mistake 3Forgetting static member initialization outside class: int Counter::count = 0; is mandatory — omitting this causes a linker error.
P4

Practice — Data Types, Control, Loops & Arrays

🟢 Basic Level

💻 Coding Q1 — Array + Loop

Write a program that stores 5 integers in an array, finds the largest element, and prints it.

#include<iostream>
using namespace std;
int main(){
    int arr[5]={12,45,7,33,28};
    int max=arr[0];
    for(int i=1;i<5;i++)
        if(arr[i]>max) max=arr[i];
    cout<<"Largest: "<<max;
    return 0;
}
Output
Largest: 45
💻 Coding Q2 — static variable

Write a function countCalls() using a static variable that tracks how many times it is called. Call it 4 times and print the count each time.

#include<iostream>
using namespace std;
void countCalls(){
    static int n=0;
    n++;
    cout<<"Call #"<<n<<endl;
}
int main(){
    countCalls(); countCalls(); countCalls(); countCalls();
    return 0;
}
Output
Call #1 Call #2 Call #3 Call #4

🔴 Output Trap — Loop Edge Case

⚠ What is the output?
int main(){
    int i=5;
    do{ cout<<i<<" "; i--; }
    while(i>7);
    cout<<"end";
}

Output: 5 end
do-while runs ONCE (prints 5, i becomes 4) THEN checks condition: 4 > 7 is false, so loop ends. "end" prints.

Mistake 1 — Array IndexArray of size 5: valid indices are 0,1,2,3,4. Writing arr[5] is out-of-bounds — undefined behavior, no compile error but wrong results.
Mistake 2 — switch without breakForgetting break in switch causes fall-through — all cases below the matched one also execute.
Mistake 3 — Type Castingint y = (int)9.9; gives 9, not 10. Casting truncates — does NOT round.

Input-Based Programs — OOP Concepts

Program 1 — Input: Class with cin

#include<iostream>
using namespace std;
class Student{
private:
    string name; int marks;
public:
    void input(){
        cout<<"Enter name: "; cin>>name;
        cout<<"Enter marks: "; cin>>marks;
    }
    void display(){
        cout<<"Name: "<<name<<" | Marks: "<<marks;
        if(marks>=50) cout<<" | PASS"<<endl;
        else cout<<" | FAIL"<<endl;
    }
};
int main(){
    Student s;
    s.input();
    s.display();
    return 0;
}
Sample Output (input: Ali 75)
Enter name: Ali Enter marks: 75 Name: Ali | Marks: 75 | PASS

Program 2 — Input: Encapsulation with getter/setter

#include<iostream>
using namespace std;
class BankAccount{
private: double balance;
public:
    BankAccount(){ balance=0; }
    void deposit(){
        double amt;
        cout<<"Enter deposit amount: "; cin>>amt;
        balance+=amt;
        cout<<"Balance: "<<balance<<endl;
    }
    void withdraw(){
        double amt;
        cout<<"Enter withdraw amount: "; cin>>amt;
        if(amt>balance) cout<<"Insufficient!"<<endl;
        else{ balance-=amt; cout<<"Balance: "<<balance<<endl; }
    }
};
int main(){
    BankAccount acc;
    acc.deposit();
    acc.withdraw();
    return 0;
}
Sample Output (inputs: 1000, 300)
Enter deposit amount: 1000 Balance: 1000 Enter withdraw amount: 300 Balance: 700

Program 3 — Input: Inheritance with user data

#include<iostream>
using namespace std;
class Person{
public:
    string name; int age;
    void input(){ cout<<"Name: "; cin>>name; cout<<"Age: "; cin>>age; }
    void display(){ cout<<"Name:"<<name<<" Age:"<<age<<endl; }
};
class Employee:public Person{
public:
    int id;
    void inputEmp(){ input(); cout<<"EmpID: "; cin>>id; }
    void displayEmp(){ display(); cout<<"EmpID:"<<id<<endl; }
};
int main(){
    Employee e;
    e.inputEmp();
    e.displayEmp();
    return 0;
}
Sample Output (inputs: Arun 25 101)
Name: Arun Age: 25 EmpID: 101 Name:Arun Age:25 EmpID:101

Loop & Array Problems

🟢 Basic — Sum of Array

#include<iostream>
using namespace std;
int main(){
    int n; cout<<"How many numbers? "; cin>>n;
    int arr[100], sum=0;
    for(int i=0;i<n;i++){ cout<<"Enter: "; cin>>arr[i]; sum+=arr[i]; }
    cout<<"Sum="<<sum<<" Average="<<(float)sum/n;
    return 0;
}
Sample Output (n=3, values: 10 20 30)
Sum=60 Average=20

🟡 Medium — Max & Min in Array

#include<iostream>
using namespace std;
int main(){
    int arr[5]={23,7,45,12,38};
    int mx=arr[0], mn=arr[0];
    for(int i=1;i<5;i++){
        if(arr[i]>mx) mx=arr[i];
        if(arr[i]<mn) mn=arr[i];
    }
    cout<<"Max="<<mx<<" Min="<<mn;
    return 0;
}
Output
Max=45 Min=7

🔴 Exam-Level — Pattern Printing

#include<iostream>
using namespace std;
int main(){
    int n=5;
    for(int i=1;i<=n;i++){
        for(int j=1;j<=i;j++) cout<<"* ";
        cout<<endl;
    }
    return 0;
}
Output
* * * * * * * * * * * * * * *

🔵 Array Traversal — Reverse Print

#include<iostream>
using namespace std;
int main(){
    int arr[5]={10,20,30,40,50};
    cout<<"Reverse: ";
    for(int i=4;i>=0;i--) cout<<arr[i]<<" ";
    return 0;
}
Output
Reverse: 50 40 30 20 10
💻 Array Practice — Try These

Q1: Write a program to count even and odd numbers in an array of 6 elements.

Q2: Write a program to print the multiplication table of a number entered by user.

Q3 (Output trap): What does this print? for(int i=0;i<3;i++) cout<<i*i<<" ";

Output: 0 1 4 — i=0:0*0=0, i=1:1*1=1, i=2:2*2=4

UML — Exam Drawing Guide & Practice

✍ How to Draw UML Class Diagram in Exam (Step-by-Step)

Write-From-Scratch — UML in Exam
Step 1: Draw a rectangle divided into 3 parts
Step 2: Top part → write ClassName
Step 3: Middle part → write attributes with - (private) or + (public) prefix and type
Step 4: Bottom part → write methods with + prefix, parameters, and return type
Step 5: If inheritance → draw arrow from Child to Parent (hollow arrowhead pointing to Parent)

Solved Example — Student UML → Code

UML Class Diagram

+---------------------------+
|         Student           |
+---------------------------+
| - rollNo : int            |
| - name   : string         |
| - marks  : float          |
+---------------------------+
| + setData(int,string,float): void |
| + display() : void        |
| + getGrade() : char       |
+---------------------------+
#include<iostream>
using namespace std;
class Student{
private:
    int rollNo; string name; float marks;
public:
    void setData(int r,string n,float m){ rollNo=r; name=n; marks=m; }
    void display(){ cout<<rollNo<<" "<<name<<" "<<marks<<" "<<getGrade()<<endl; }
    char getGrade(){
        if(marks>=90) return 'A';
        else if(marks>=75) return 'B';
        else return 'C';
    }
};
int main(){
    Student s;
    s.setData(101,"Arun",88.5);
    s.display();
    return 0;
}
Output
101 Arun 88.5 B

📄 UML Practice Scenario

✍ Draw the UML Diagram for this scenario

Scenario: A Library system has a Book class with private attributes: title (string), author (string), price (float). It has public methods: setBook(), displayBook(), and getPrice() which returns float. A EBook class inherits from Book and adds fileSize (int, private) and download() (public).

+---------------------------+        +---------------------------+
|          Book             |        |          EBook            |
+---------------------------+        +---------------------------+
| - title  : string         |  <|--  | - fileSize : int          |
| - author : string         |        +---------------------------+
| - price  : float          |        | + download() : void       |
+---------------------------+        +---------------------------+
| + setBook() : void        |
| + displayBook() : void    |
| + getPrice() : float      |
+---------------------------+

Arrow (hollow) points FROM EBook TO Book = Inheritance

Output Traps — Advanced

Trap 1 — Operator Precedence

⚠ Predict the Output
int main(){
    int a=10, b=3;
    cout<<a/3<<" "<<a%b<<" "<<(float)a/b;
}

Output: 3 1 3.33333
a/3 = integer division = 3. a%b = 10%3 = 1. (float)a/b = 10.0/3 = 3.33333

Trap 2 — Access Specifier Error

⚠ Will this compile? What happens?
class A{
    int x=5;   // no specifier = private
public:
    void show(){ cout<<x; }
};
int main(){
    A obj;
    cout<<obj.x;   // line A
    obj.show();    // line B
}

Line A → Compile Error (x is private, cannot access outside class)
Line B → OK, prints: 5 (show() is public, it CAN access private x from inside class)

Trap 3 — Constructor Trap

⚠ What is the output?
class A{
public:
    A(){ cout<<"A created\n"; }
    ~A(){ cout<<"A destroyed\n"; }
};
int main(){
    A x;
    cout<<"Inside main\n";
}

Output:
A created
Inside main
A destroyed

Constructor called when x created. Destructor auto-called when x goes out of scope (main ends).

Trap 4 — Static Trap

⚠ What prints?
void test(){
    static int x=1;
    cout<<x++<<" ";
}
int main(){ test(); test(); test(); }

Output: 1 2 3
Static x initializes to 1 ONCE. Each call prints current x (post-increment), then increments. x persists: 1→2→3.

Write-From-Scratch Exam Guides

Guide 1 — How to write Encapsulation in exam
1. #include<iostream> + using namespace std;
2. class ClassName {
3. private: — declare data members
4. public: — write setter (void setX(type v){x=v;}) and getter (type getX(){return x;})
5. }; — DON'T forget semicolon
6. main(): create object → call setter → call getter/display
Guide 2 — How to write Inheritance in exam
1. Write base class completely first
2. Write: class Child : public Base {
3. Add child-specific members inside
4. };
5. main(): create Child object → it can call BOTH base AND child methods
Guide 3 — How to write Polymorphism in exam
1. In base class, add virtual before the method: virtual void show(){}
2. In each derived class, OVERRIDE: void show(){ /* different code */ }
3. main(): create each derived class object → call show() → each gives different output
Guide 4 — How to write Array + Loop in exam
1. Declare: int arr[n] = {v1,v2,...};
2. For loop: for(int i=0; i<n; i++) — remember i starts at 0
3. Access: arr[i]
4. Last valid index = n-1 (NOT n)
Guide 5 — How to write UML in exam
1. 3-part rectangle: ClassName | attributes | methods
2. prefix: - (private), + (public), # (protected)
3. Format: - varName : type and + methodName(params) : returnType
4. Inheritance arrow: hollow triangle pointing TO parent class
🔒

Final Revision Block — Unit 1 Complete

📅 Key Definitions — One Line Each

OOAD: Methodology to analyze (what) and design (how) software using objects.

OOP: Programming approach using objects with attributes and methods.

Class: Blueprint/template that defines data and behavior.

Object: Instance of a class with its own copy of data.

Encapsulation: Private data + public methods = data hiding.

Inheritance: Child class acquires parent class properties. Syntax: class C : public P {};

Polymorphism: Same method, different behavior per object. Needs virtual.

Abstraction: Hide HOW, show WHAT. Pure virtual (=0) makes class abstract.

Constructor: Same name as class, no return type, auto-called on object creation.

Static method: Belongs to class, not object. Called as Class::method().

Access specifiers: public=all, private=class only, protected=class+children.

UML Class Diagram: +public -private #protected. Shows class structure visually.

⚡ Quick Syntax Cheat Sheet

// Class + Object
class Name{ private: int x; public: void set(int a){x=a;} }; Name obj; obj.set(5);

// Inheritance
class Child : public Parent { };

// Polymorphism
class Base{ public: virtual void f(){} };
class Der:public Base{ public: void f() override {} };

// Abstraction (pure virtual)
class Abs{ public: virtual void f() = 0; };

// Constructor
class A{ public: A(){ cout<<"Created"; } };

// Static
class A{ public: static int n; static void f(){} }; int A::n=0; A::f();

// Outside method
class A{ public: void show(); }; void A::show(){ cout<<"Hi"; }

// Array
int arr[5]={1,2,3,4,5}; arr[0]=first; arr[4]=last;

💥 Top 10 Output Traps to Remember

1. a++ = use then increment  |  ++a = increment then use

2. do-while always runs at least ONCE even if condition is false

3. (int)9.9 = 9 (truncates, does NOT round)

4. switch without break = fall-through (all cases below match also run)

5. No virtual = base class method always called through base pointer

6. Abstract class cannot be instantiated — compile error

7. Array index out of bounds = undefined behavior (no compile error)

8. Default in class = private | Default in struct = public

9. Static variable initializes ONCE, retains value across all calls

10. Forgetting ; after class closing brace = compile error

🎯 Exam-Level Questions — Final Practice

💻 Exam Q1 — 10 marks program

Write a complete C++ program with: (a) Base class Shape with virtual method area(). (b) Derived classes Circle (radius) and Rectangle (length, width) that override area(). (c) Use constructors to initialize. (d) Call area() for both shapes in main.

#include<iostream>
using namespace std;

class Shape{
public:
    virtual void area() = 0;  // pure virtual = abstract
};

class Circle : public Shape{
private: float radius;
public:
    Circle(float r){ radius=r; }
    void area(){ cout<<"Circle area="<<3.14*radius*radius<<endl; }
};

class Rectangle : public Shape{
private: float length,width;
public:
    Rectangle(float l,float w){ length=l; width=w; }
    void area(){ cout<<"Rectangle area="<<length*width<<endl; }
};

int main(){
    Circle c(5);
    Rectangle r(4,6);
    c.area();
    r.area();
    return 0;
}
Output
Circle area=78.5 Rectangle area=24
💻 Exam Q2 — Full OOP Program

Create a class Student with: private name & marks, constructor to initialize, static member totalStudents incremented in constructor, public method to display. Create 2 students and show total count.

#include<iostream>
using namespace std;

class Student{
private:
    string name; int marks;
public:
    static int totalStudents;
    Student(string n, int m){
        name=n; marks=m; totalStudents++;
    }
    void display(){
        cout<<"Name:"<<name<<" Marks:"<<marks<<endl;
    }
};
int Student::totalStudents=0;

int main(){
    Student s1("Arun",85);
    Student s2("Priya",92);
    s1.display(); s2.display();
    cout<<"Total Students: "<<Student::totalStudents;
    return 0;
}
Output
Name:Arun Marks:85 Name:Priya Marks:92 Total Students: 2

🔒 Memory Lock — Final 10 Lines

Memory Lock — Unit 1 Complete 1. Class=blueprint | Object=instance | ; after } is mandatory
2. EIPA = Encapsulation Inheritance Polymorphism Abstraction
3. private=class only | protected=class+child | public=everywhere
4. virtual = runtime polymorphism | =0 = pure virtual = abstract class
5. Constructor: same name, no return, auto-called
6. Static: belongs to class, one copy, init outside: Type Class::var=0;
7. Inheritance: class Child : public Parent { };
8. :: = scope resolution (outside method OR static call)
9. Array index 0 to n-1 | do-while runs at least once
10. UML: + public | - private | # protected

P1

Practice — OOP Basics

✍️ Write From Scratch
Basic — 5 Marks
Write a class Rectangle with private members length and width (float). Add a constructor, area(), and perimeter(). Create an object and display both values.
#include<iostream>
using namespace std;
class Rectangle{
    float length, width;
public:
    Rectangle(float l,float w){ length=l; width=w; }
    float area(){ return length*width; }
    float perimeter(){ return 2*(length+width); }
};
int main(){
    Rectangle r(5,3);
    cout<<"Area: "<<r.area()<<"\n";
    cout<<"Perimeter: "<<r.perimeter();
}
▶ Output
Area: 15 Perimeter: 16
Medium — 8 Marks
Write a class Student with private: name (string), marks[5] (int). Public: constructor, getAverage(), getGrade() (A>=80, B>=60, else C), display(). Create one student and display all info.
#include<iostream>
using namespace std;
class Student{
    string name; int marks[5];
public:
    Student(string n, int m[]){ name=n; for(int i=0;i<5;i++) marks[i]=m[i]; }
    float getAverage(){ int s=0; for(int i=0;i<5;i++) s+=marks[i]; return s/5.0; }
    string getGrade(){ float a=getAverage(); return a>=80?"A":a>=60?"B":"C"; }
    void display(){ cout<<name<<" Avg:"<<getAverage()<<" Grade:"<<getGrade()<<"\n"; }
};
int main(){ int m[]={85,70,90,65,80}; Student s("Ali",m); s.display(); }
▶ Output
Ali Avg:78 Grade:B
Tricky — 10 Marks
Create a base class Animal with virtual void speak(). Derive Dog and Cat, each overriding speak(). Use a Animal* array to hold both and call speak() polymorphically.
#include<iostream>
using namespace std;
class Animal{ public: virtual void speak()=0; };
class Dog:public Animal{ public: void speak(){ cout<<"Woof!\n"; } };
class Cat:public Animal{ public: void speak(){ cout<<"Meow!\n"; } };
int main(){
    Animal* a[2]={ new Dog(), new Cat() };
    for(int i=0;i<2;i++) a[i]->speak();
}
▶ Output
Woof! Meow!
P2

Predict Output — Core Mechanics

⚡ Predict the Output — Think Before You Click!
Trap 1 — Post vs Pre Increment
int a=5, b=3;
cout<<a++<<" "<<++b<<" "<<a<<" "<<b;

Output: 5 4 6 4
a++ prints 5 THEN increments → a becomes 6. ++b increments FIRST → b becomes 4, prints 4.

Trap 2 — Access Specifiers Default
class X{ int x=10; public: void show(){ cout<<x; } };
int main(){ X obj; cout<<obj.x; // Line A
obj.show(); // Line B }

Line A → Compile ERROR — x has no specifier in a class, defaults to private.
Line B → Prints: 10 — show() is public and accesses private x from inside.

Trap 3 — Static Member Counter
class C{ public: static int n; C(){ n++; } };
int C::n=0;
int main(){ C a,b,c; cout<<C::n; }

Output: 3
Each object creation calls the constructor which does n++. Three objects → n=3. Static n is shared by ALL objects.

Trap 4 — Inheritance + Virtual Dispatch
class B{ public: virtual void f(){ cout<<"B"; } };
class D:public B{ public: void f(){ cout<<"D"; } };
int main(){ B* p=new D; p->f(); }

Output: D
virtual enables late binding. Even though pointer is B*, actual object is D → D::f() runs.

Trap 5 — Do-While Loop
int i=5;
do{ cout<<i<<" "; i++; }while(i<3);

Output: 5
do-while runs the body FIRST, then checks condition. Body runs once (prints 5, i becomes 6). Condition 6<3 is false → stops. Key: do-while always runs at least once.

P3

Debug This — Find & Fix the Bugs

🐛 Spot Every Bug. Fix It. Understand Why.
Bug 1 — Missing Semicolon After Class
class Car{
public:
    int speed;
}   // BUG HERE
int main(){ Car c; c.speed=100; }

Bug: Missing ; after closing brace of class.
Fix: Change } to };
Rule: In C++, class definitions MUST end with a semicolon. This is one of the most common errors.

Bug 2 — Accessing Private Member
class Box{
    int size = 10;
};
int main(){ Box b; cout<<b.size; // BUG }

Bug: size is private (class default). Cannot access outside.
Fix: Either add public: before int size, or add a public getter: int getSize(){ return size; }

Bug 3 — Static Member Not Defined Outside
class A{ public: static int count; A(){ count++; } };
int main(){ A x,y; cout<<A::count; } // BUG: linker error

Bug: Static member declared but not defined outside the class.
Fix: Add before main: int A::count = 0;
Rule: Static members must be defined outside the class body, even if initialized inside.

Bug 4 — Inheritance Visibility
class Animal{ protected: string name; };
class Dog:private Animal{
public: void show(){ cout<<name; } // this is fine
};
int main(){ Dog d; Animal* p=&d; } // BUG

Bug: private inheritance hides the base class. You cannot convert Dog* to Animal*.
Fix: Change private Animal to public Animal.
Rule: For polymorphism (base pointer = derived object), you MUST use public inheritance.

P4

Edge Cases You MUST Know

⚠️ Critical Traps — Exam Favourites

1. struct vs class Default Access

struct S{ int x; };  // x is PUBLIC by default
class  C{ int x; };  // x is PRIVATE by default
Rule: struct defaults to public. class defaults to private. This is the ONLY difference between struct and class in C++.

2. Uninitialized Variable = Garbage Value

int main(){ int x; cout<<x; }  // prints garbage (undefined behaviour)
Rule: Always initialize variables. int x = 0; Always initialize class members in constructor.

3. Non-virtual Method — No Polymorphism

class B{ public: void show(){ cout<<"B"; } };
class D:public B{ public: void show(){ cout<<"D"; } };
int main(){ B* p=new D; p->show(); }  // prints "B" not "D"!
Rule: Without virtual, pointer type determines which method is called (static binding). With virtual, actual object type determines it (dynamic binding).

4. Array Out of Bounds — No Runtime Error, Just Garbage

int arr[3]={1,2,3};
cout<<arr[5];  // No error! Just random memory value
Rule: C++ does NOT check array bounds. Accessing out-of-bounds is undefined behaviour — no error is thrown, just garbage or crash.

5. Integer Division Truncates

int a=7, b=2;
cout<<a/b;   // prints 3, NOT 3.5!
cout<<(float)a/b;  // prints 3.5 (cast first!)
Fix: Cast to float before dividing: (float)a/b or use 7.0/2.
P5

Active Recall — Test Yourself

🧠 Rapid-Fire Theory — Click to Reveal Answers
1. What are the 4 pillars of OOP?
Encapsulation, Inheritance, Polymorphism, Abstraction (EIPA). Remember: "Every Incredible Program Abstracts".
2. What is the difference between a class and an object?
A class is a blueprint/template. An object is a real instance of that class created in memory. Class = recipe. Object = actual dish.
3. What are the three access specifiers in C++?
public — accessible everywhere. private — accessible only inside the class. protected — accessible inside the class and its derived classes.
4. What does virtual do? When is it needed?
virtual enables runtime polymorphism (late/dynamic binding). Needed when you want a base class pointer to call the derived class's overridden method.
5. What is a pure virtual function? What class does it create?
virtual void func() = 0; — A pure virtual function. A class with at least one pure virtual function becomes an abstract class. Abstract classes cannot be instantiated directly.
6. How is a static member different from a regular member?
Static members belong to the class itself, not to any object. One shared copy for all objects. Must be defined outside the class: Type Class::var = 0;. Accessed via Class::member.
7. What is the scope resolution operator :: used for?
1. Define methods outside the class: void Class::method(){ }. 2. Access static members: Class::staticVar. 3. Call base class method explicitly: Base::method().
8. In UML class diagrams, what do +, -, # mean?
+ = public. - = private. # = protected. Format: +methodName(params) : returnType.
9. What is inheritance syntax in C++?
class Derived : public Base { }; — The colon means "inherits from". Use public inheritance for polymorphism. Derived class gets all public and protected members of Base.
10. What is the difference between early binding and late binding?
Early (static) binding: function call resolved at compile time — no virtual. Late (dynamic) binding: resolved at runtime via vtable — requires virtual keyword.
P6

Final Exam Coding Programs

Question 1
Bank Account Class
10 Marks
Write a class BankAccount with private: owner, balance. Public: constructor, deposit(float), withdraw(float) (check if balance sufficient), display(). Create one account and do both operations.
#include<iostream>
using namespace std;
class BankAccount{
    string owner; float balance;
public:
    BankAccount(string o,float b){ owner=o; balance=b; }
    void deposit(float amt){ balance+=amt; cout<<"Deposited: "<<amt<<"\n"; }
    void withdraw(float amt){
        if(amt>balance) cout<<"Insufficient funds\n";
        else{ balance-=amt; cout<<"Withdrawn: "<<amt<<"\n"; }
    }
    void display(){ cout<<owner<<" Balance: "<<balance<<"\n"; }
};
int main(){
    BankAccount acc("Ali",1000);
    acc.deposit(500); acc.withdraw(200); acc.display();
}
▶ Output
Deposited: 500 Withdrawn: 200 Ali Balance: 1300
Question 2
Shape Hierarchy with Polymorphism
12 Marks
Create abstract class Shape with pure virtual area() and perimeter(). Derive Circle and Rectangle. Use a Shape* array to store both and call methods polymorphically.
#include<iostream>
using namespace std;
class Shape{ public: virtual float area()=0; virtual float perimeter()=0; };
class Circle:public Shape{
    float r;
public:
    Circle(float r){ this->r=r; }
    float area(){ return 3.14*r*r; }
    float perimeter(){ return 2*3.14*r; }
};
class Rectangle:public Shape{
    float l,w;
public:
    Rectangle(float a,float b){ l=a; w=b; }
    float area(){ return l*w; }
    float perimeter(){ return 2*(l+w); }
};
int main(){
    Shape* s[2]={ new Circle(7), new Rectangle(4,5) };
    for(int i=0;i<2;i++) cout<<"Area:"<<s[i]->area()<<" Perimeter:"<<s[i]->perimeter()<<"\n";
}
▶ Output
Area:153.86 Perimeter:43.96 Area:20 Perimeter:18
P7

Complete Programs — Full Execution Flow

💻 Program 1 — Student Grading with Arrays
#include<iostream>
using namespace std;
class Student{
    string name; int marks[5]; static int count;
public:
    Student(string n, int m[]){ name=n; for(int i=0;i<5;i++) marks[i]=m[i]; count++; }
    float avg(){ int s=0; for(int i=0;i<5;i++) s+=marks[i]; return s/5.0; }
    string grade(){ float a=avg(); return a>=80?"A":a>=60?"B":"C"; }
    void display(){ cout<<name<<" | Avg:"<<avg()<<" | Grade:"<<grade()<<"\n"; }
    static int getCount(){ return count; }
};
int Student::count=0;
int main(){
    int m1[]={85,70,90,65,80};
    int m2[]={50,45,60,55,40};
    Student s1("Ali",m1), s2("Sara",m2);
    s1.display(); s2.display();
    cout<<"Total students: "<<Student::getCount();
}
▶ Output
Ali | Avg:78 | Grade:B Sara | Avg:50 | Grade:C Total students: 2
🧠 Dry Run Trace
Student s1 createdconstructor runs: name="Ali", marks copied, count++ → count=1
Student s2 createdconstructor runs: name="Sara", marks copied, count++ → count=2
s1.display()calls avg(): 85+70+90+65+80=390/5=78. grade(): 78<80 → 78>=60 → "B"
s2.display()calls avg(): 50+45+60+55+40=250/5=50. grade(): 50<60 → "C"
Student::getCount()static method returns shared count=2. No object needed to call it.

🚀 Live C++ Compiler