OOAD — Object-Oriented Analysis and Design
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 |
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;
}
Arun issued: C++ Primer
Book not available!
Arun returned: C++ Primer
Book (has
title, availability) and Member (has name, can borrow).Book stores state;
Member provides behavior (methods).issueBook method uses logic to protect the book's available
state.main, we create instances (b1, m1) and simulate the library workflow.
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; }
Arun issued: C++ Primer
Not available!
// OOA/OOD Demo
class Book { public: string title; };
Think: Architect (OOA=requirements, OOD=blueprint)
OOP — Object-Oriented Programming Basics
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;
}
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;
}
Rex says: Woof!
Name: Rex, Age: 3
Max says: Woof!
Name: Max, Age: 5
Dog is the blueprint. It doesn't take memory until
an object is made.d1 and d2 are instances. Each has its
OWN name and age.d1.name sets only
d1's data.bark() use the data of the specific object they were called on.
#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;
}
Rex says: Woof!
Name: Rex, Age: 3
Max says: Woof!
Name: Max, Age: 5
class Dog defines attributes
(name,age) and methods (bark(),info()). No memory
allocated yet.Dog d1, d2 creates two dogs. Each gets
its own copy of name and age in memory.d1.name="Rex" stores 'Rex' in d1's memory. d2 is unaffected.d1.bark() — inside bark(), name refers to d1's name
(Rex). Output: Rex says: Woof!#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; }
Rex says Woof!
class Dog { public: string name; void bark(){ cout<<"Woof"; } };
Woof
EIPA = Encapsulation, Inheritance, Polymorphism, Abstraction
Quick Check (click to reveal)
What is the difference between a class and an object?
Name the 4 pillars of OOP.
Encapsulation
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;
}
Account: Alice | Balance: 1000
Deposited: 500 | Balance: 1500
Withdrawn: 200 | Balance: 1300
balance is private — cannot be changed from outside the class
directly.deposit() and withdraw() are public — they are the
only controlled ways to access balance.acc.balance = 99999 outside the class gives a compile error — that's
encapsulation protecting the data.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;
}
Marks: 85
Invalid marks!
private: makes marks inaccessible from main().
setMarks() acts as a gatekeeper (Setter). It validates data before saving.
getMarks() provides read-only access (Getter).#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;
}
Marks: 85
Invalid!
Current: 85
private int marks — completely hidden. Writing s.marks=90
outside the class gives a compile error.setMarks() is a setter with built-in validation. Only valid values
(0–100) are accepted.s.setMarks(85) — 85 is valid → stored. marks=85.
s.setMarks(150) — 150 > 100 → rejected. marks stays 85. This
is data protection.getMarks() is a getter — allows reading but not tampering.
Encapsulation = private data + public controlled access.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; }
90
class Student { private: int m; public: void set(int x){ m=x; } };
Capsule = chemicals hidden inside = data hidden inside class
Inheritance
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;
}
Speed: 120 | Fuel: 40
Car has Air Conditioning
Speed: 80 | Fuel: 15
Bike requires Helmet
speed, fuel, setData(),
and display() from Vehicle — no need to rewrite.: public Vehicle means Car is a Vehicle — it gets all public members of
Vehicle.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;
}
Name: Priya Salary: 50000
Priya's total = 60000
class Manager : public Employee — the colon means 'inherits from'.
Manager gets ALL public members of Employee.m.setData() — defined in Employee, used by Manager. No rewriting
needed. This is code reuse.m.display() — also from Employee. Manager didn't define it but can
call it.m.bonus and showTotal() — Manager's own additions on top
of Employee.#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; }
Arun 101
class A {}; class B : public A {};
: public Parent = "I am a type of Parent"
No rewriting = Code reuse
Polymorphism
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;
}
Teacher teaches students
Student learns from teacher
virtual keyword in the base class allows the child class to override the
method.getRole() but each prints different output —
same method name, different behavior.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;
}
Drawing Circle O
Drawing Rectangle []
virtual void draw() in Shape — tells C++: decide which version to call
at RUNTIME based on the actual object.draw() with their own version.Shape* ptr — a base class pointer that can point to any Shape-derived
object.ptr=&c; ptr->draw() — ptr points to Circle. Virtual dispatch
checks actual type → calls Circle::draw().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; }
Circle
class S { virtual void d(); };
virtual keyword = "child can override this"
Abstraction
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;
}
TV is turned ON
AC is set to 22 degrees
Remote is an abstract class — it has a pure virtual function
(= 0). Cannot be instantiated directly.pressButton(). The user
only calls the button — doesn't know how it works internally.Remote r; gives compile error. Only derived classes that override all pure virtual functions can be
instantiated.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;
}
Car: vroom!
Car: stopped.
Boat: splash!
Boat: anchored.
virtual void start() = 0 — pure virtual. The = 0 makes
Vehicle abstract. It defines WHAT to do, not HOW.Vehicle v; would cause a compile error — you cannot instantiate an
abstract class.start() and stop()
implementations.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; }
Car started
class V { virtual void s()=0; };
Abstract class + pure virtual (= 0) = abstraction in C++
Cannot create object of abstract class directly
Classes and Objects in C++
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;
}
Student 1:
Name: Arun
Marks: 85
Student 2:
Name: Priya
Marks: 92
name, marks,
setData(), displayData().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;
}
Rectangle 1:
Width: 5 Height: 3
Area: 15 Perimeter: 16
Rectangle 2:
Width: 10 Height: 4
Area: 40 Perimeter: 28
private double width, height — data is hidden. Cannot access
r1.width directly from main().setDimensions() is the setter. Both r1 and r2 call it with different values
— each stores independently.area() and perimeter() compute from the object's own private
data.display() calls area() and perimeter() internally
— member functions can call other member functions.#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; }
50
Dot operator (.) = access object members
private = hidden | public = accessible
Access Specifiers
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;
}
Marks: 85
Roll No: 101
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;
}
Name: Alice Age: 20
Name: Bob Age: 18
Hi, I am Bob
private int age — only Person's own methods can read/write age. Even
Student (child) cannot access it.protected string name — Person + Student can access it. Outside main()
cannot.public setData()/display() — accessible everywhere. These are the safe
entry points.name is accessible (protected), but age
would cause a compile error (private).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; }
(Compilation only)
Default in class = private | Default in struct = public
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;
}
Student created with ID: 101
Student created with ID: 102
Student ID: 101
Student ID: 102
College: SRM University
Student(int i) runs automatically when s1 and s2 are created —
no need to call it manually.showId() is inline — compiler replaces the call with the function body
directly for speed.showCollege() is static — called with Student::showCollege(),
not through an object. Same college for all students.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;
}
Object 1 created
Object 2 created
Count: 2
Count: 1
Total objects: 2
Counter(): auto-called when c1 and c2 are
created. Initializes count=0 and increments shared total.int Counter::total = 0: static members must be defined outside the class
(just once).#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; }
2
Static = belongs to class (::), not object
Inline = fast, body pasted at call point
I/O Operations in C++
cout 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;
}
Enter your name: Alice
Enter your age: 20
Name: Alice
Age: 20
<< (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;
}
Enter Roll No: 101
Enter Name: Arun
Enter Marks: 78
--- Student Report ---
Roll No : 101
Name : Arun
Marks : 78
Result : PASS
cout << "Enter Roll No: " — insertion operator sends text to
screen. No newline until endl.cin >> rollNo — extraction operator waits for keyboard input and
stores it in rollNo.cin >> name — reads one word (stops at space). For full name
with spaces use getline(cin, name).cout << rollNo << endl — chain multiple values with
<<. endl flushes and moves to new line.#include <iostream>
using namespace std;
int main(){ int n; cout<<"Enter n: "; cin>>n; cout<<"Value is "<<n; return 0; }
Enter n: 5
Value is 5
cout << = output (variable prints to screen)
Header: #include <iostream> always required
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;
}
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;
}
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
int age=20 — 4 bytes, whole numbers only. Range: -2 billion to +2
billion.float height=5.9f — 4 bytes, 6 decimal digits. The 'f' suffix marks it
as float literal.double pi=3.14159265 — 8 bytes, 15 decimal digits. More precise than
float.char grade='A' — 1 byte, stores a single character. Single quotes for
char, double for string.bool pass=true — cout prints 1 for true, 0 for false.(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; }
Implicit = auto (int to float) | Explicit = manual (float to int)
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;
}
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;
}
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;
}
Student 1: 80
Student 2: 75
Student 3: 90
Student 4: 85
Student 5: 70
#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;
}
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
int marks[5]={...} — array of 5 integers. Index 0–4. Stored
contiguously in memory.for(int i=0; i<5; i++) — runs exactly 5 times. i goes 0,1,2,3,4
matching array indices.sum += marks[i] — accumulates total each iteration.(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; }
15
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;
}
Roll: 101 Name: Arun Marks: 88.5 Grade: B
Roll: 102 Name: Priya Marks: 92 Grade: A
- means private,
+ means public.private: int rollNo; string name; float marks;public: setData(), getGrade(), display()getGrade() returns a string based on marks — notice member functions
can call other member functions.UML Diagrams
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;
}
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 |
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(); };
(Structure only)
Use Case = WHO does WHAT | Sequence = WHO talks to WHOM when
Activity = STEP BY STEP flow