Introduction to Object Oriented Programming
Open in the Padhaiko app1.1 History of programming languages
Programming languages evolved across successive generations to bridge the gap between raw hardware instructions and human problem solving. Each paradigm shift addressed the complexity limits of the previous era.
| Generation / Paradigm | Representative Languages | Key Characteristics | Primary Limitation |
|---|---|---|---|
| 1GL — Machine Language | Binary opcodes (0s and 1s) | Directly executed by CPU; zero translation needed | Hardware-dependent, extremely error-prone, unreadable |
| 2GL — Assembly Language | x86, 8085 Assembly | Symbolic mnemonics (MOV, ADD); translated by an assembler | Still machine-specific; tedious for large applications |
| 3GL — Unstructured / Early High-Level | FORTRAN, COBOL, BASIC | English-like statements; portable across machines | Heavy reliance on GOTO created tangled "spaghetti code" |
| Structured / Procedure-Oriented (POP) | C, Pascal, ALGOL | Top-down decomposition into functions, loops, and blocks | Data is separated from functions; global data is exposed |
| Object-Oriented (OOP) | Simula 67, Smalltalk, C++, Java | Bottom-up design bundling data and methods into objects | Larger design effort and runtime/memory overhead for small tasks |
Milestones Leading to C++ and OOP
- Simula 67 (1967): Developed by Ole-Johan Dahl and Kristen Nygaard for discrete-event simulation; introduced the foundational ideas of classes and objects.
- Smalltalk (1970s): Created at Xerox PARC by Alan Kay and team; established pure OOP where everything is an object communicating by message passing.
- C with Classes -> C++ (1979–1983): Bjarne Stroustrup at Bell Labs added Simula-style classes, strong type checking, and inheritance to the fast, low-level C language, renaming it C++ in 1983 (
++being C's increment operator).
1.2 Need of object oriented programming (OOP)
As software systems grew from thousands to millions of lines of code, Procedure-Oriented Programming (POP) hit structural limits that motivated OOP:
- Unprotected Global Data: In POP, data shared across multiple functions is declared globally. Any function can accidentally corrupt that data, making debugging difficult in large teams.
- Separation of Data and Behaviour: Functions and data structures are kept separate. Changing a record's layout forces updates to every function that touches it.
- Poor Modelling of Real-World Entities: Real-world systems consist of interacting entities (accounts, vehicles, sensors) that possess both attributes and actions. Breaking everything strictly into procedures hides these natural boundaries.
- Limited Code Reusability and Extensibility: Extending an existing procedural module often requires modifying tested source code rather than cleanly building upon it.
- High Maintenance Cost: Tight coupling between functions and global variables creates ripple effects whenever requirements change.
1.3 Object oriented programming versus procedure oriented programming
In Procedure-Oriented Programming (POP), a program is viewed as a sequence of instructions grouped into functions, and data flows from function to function. In Object-Oriented Programming (OOP), a program is organized as a collection of interacting objects, each encapsulating its own data and the operations allowed on that data.
| Aspect | Procedure-Oriented Programming (POP) | Object-Oriented Programming (OOP) |
|---|---|---|
| Primary Emphasis | Algorithms and sequence of actions (doing things) | Data and the objects that own it (things being modelled) |
| Program Division | Divided into small units called functions | Divided into entities called objects (from classes) |
| Design Approach | Top-down approach | Bottom-up approach |
| Data Security | Global data moves freely and is vulnerable to accidental change | Data can be kept private inside an object (data hiding) |
| Access Specifiers | No access control (public/private/protected) | Explicit access control (private, protected, public) |
| Overloading & Polymorphism | Not supported natively (in C) | Function overloading and operator overloading supported |
| Code Reuse Mechanism | Calling library functions | Inheritance, composition, and templates |
| Inter-module Communication | Function calls passing data arguments | Message passing between objects |
| Examples | C, Pascal, FORTRAN, COBOL | C++, Java, C#, Python, Smalltalk |
1.4 Concepts of object oriented programming
Institute of Engineering exams regularly ask for concise definitions and C++ illustrations of the core OOP concepts.
Class and Object
- Class: A user-defined blueprint or template that specifies the data members (attributes) and member functions (methods) common to all objects of that type. A class is a logical abstraction and occupies no memory for its instance data when defined.
- Object: A concrete instance of a class. When an object is created, memory is allocated for its data members, and its member functions can be invoked. Objects represent real-world entities such as a
Student,BankAccount, orMatrix.
Encapsulation and Data Abstraction
- Encapsulation: The wrapping (binding) of data and the functions that manipulate that data into a single unit (a class). Coupled with
privateaccess specifiers, encapsulation implements data hiding, preventing unauthorized external code from directly modifying internal state. - Data Abstraction: Presenting only the essential features (interface) of an object while hiding background implementation details. For example, a user calls
account.withdraw(500)without needing to know how the balance validation or ledger update is coded internally.
Inheritance, Polymorphism, Dynamic Binding, and Message Passing
- Inheritance: The mechanism by which one class (derived / child class) acquires the properties and behaviours of another class (base / parent class). It models an is-a relationship and enables hierarchical classification and code reusability.
- Polymorphism: Literally "many forms"—the ability of the same interface (function name or operator) to behave differently in different contexts:
- Compile-time (static) polymorphism: Function overloading and operator overloading.
- Run-time (dynamic) polymorphism: Virtual functions overridden in derived classes.
- Dynamic Binding (Late Binding): Linking a function call to the exact code body to execute at run time rather than compile time, based on the actual type of the object addressed by a base pointer or reference.
- Message Passing: Objects communicate by sending messages to one another—in C++, invoking a member function on an object (e.g.,
obj.display()) specifies the receiving object, the message (function name), and any arguments.
1.5 Popular object oriented languages
Object-oriented languages differ in how strictly they enforce OOP and how they execute code:
| Language | OOP Style | Execution / Typing | Notable Features & Typical Use |
|---|---|---|---|
| C++ | Hybrid (supports both POP and OOP) | Compiled, statically typed | Direct hardware/memory control, templates, zero-overhead abstraction; systems, games, embedded |
| Java | Class-based OOP | Compiled to bytecode (JVM), statically typed | Automatic garbage collection, platform independence ("write once, run anywhere"); enterprise, Android |
| Python | Multi-paradigm (everything is an object) | Interpreted, dynamically typed | Concise syntax, huge ecosystem; scripting, web backends, data science, AI |
| C# | Class-based OOP | Compiled to IL (.NET CLR), statically typed | Rich properties/events, LINQ; desktop, enterprise web, Unity game development |
| Smalltalk | Pure OOP | Virtual machine, dynamically typed | Pioneered MVC architecture and live object environments; every value including integers is an object |
| Simula 67 | First OOP language | Compiled, statically typed | Introduced classes, objects, and virtual methods for simulation |
1.6 Advantages of OOP
- Modularity: Each class forms a self-contained module with clear responsibilities, simplifying debugging and team development.
- Reusability: Through inheritance and composition, tested classes can be extended into new classes without rewriting or breaking existing code.
- Data Security (Data Hiding): Keeping attributes
privateprotects object invariants from accidental corruption by outside functions. - Extensibility and Maintainability: New object types can be added with minimal changes to existing callers, reducing maintenance costs.
- Natural Real-World Mapping: Classes mirror domain entities (e.g.,
Employee,Invoice,Sensor), making system design easier to understand and verify. - Polymorphic Flexibility: Code written against a base interface works seamlessly with new derived classes added later.
1.7 Disadvantages of OOP
- Larger Program Size and Memory Overhead: Class metadata, vtables (for virtual functions), and wrapper code typically make OOP binaries larger than equivalent C programs.
- Execution Overhead: Run-time polymorphism (dynamic dispatch) and frequent object creation/destruction can add slight latency in performance-critical tight loops if used carelessly.
- Steeper Learning Curve: Designing good class hierarchies requires understanding abstraction, inheritance rules, and object lifetimes, which is harder initially than writing linear functions.
- Overkill for Small or Strictly Sequential Tasks: Writing a short utility script or simple mathematical filter in full OOP style can introduce unnecessary boilerplate.
- Deep Inheritance Fragility: Poorly planned, overly deep inheritance trees become rigid and hard to refactor.
Worked Examples
1
Demonstrate the practical difference between Procedure-Oriented Programming and Object-Oriented Programming by modelling a bank account that prevents negative balances.
Procedure-Oriented Style (Exposed Data): In POP, the account balance is held in a struct (or global variable) with separate functions. Nothing stops external code in main() from directly assigning an invalid negative value to balance:
#include <iostream>
using namespace std;
struct BankAccountPOP {
int accNo;
double balance;
};
void deposit(BankAccountPOP &acc, double amt) {
if (amt > 0) acc.balance += amt;
}
int main() {
BankAccountPOP a1 = {101, 1000.0};
deposit(a1, 500.0);
a1.balance = -9999.0; // External code corrupts the invariant!
cout << "POP Balance: " << a1.balance << endl;
return 0;
}Object-Oriented Style (Encapsulation & Data Hiding): In OOP, balance is declared private. External code can interact with the account only through public member functions (deposit, withdraw, getBalance), which enforce valid rules:
#include <iostream>
using namespace std;
class BankAccount {
private:
int accNo;
double balance;
public:
BankAccount(int no, double initial) {
accNo = no;
balance = (initial >= 0) ? initial : 0.0;
}
void deposit(double amt) {
if (amt > 0) balance += amt;
}
bool withdraw(double amt) {
if (amt > 0 && amt <= balance) {
balance -= amt;
return true;
}
return false;
}
double getBalance() const { return balance; }
};
int main() {
BankAccount a1(101, 1000.0);
a1.deposit(500.0);
// a1.balance = -9999.0; // Compile error: balance is private!
bool ok = a1.withdraw(2000.0); // Safely rejected
cout << "Withdraw 2000 ok? " << ok << ", Balance: " << a1.getBalance() << endl;
return 0;
}In POP, a1.balance = -9999.0 succeeds and corrupts the balance to -9999. In OOP, making balance private blocks direct access at compile time, withdraw(2000.0) returns 0 (false), and getBalance() safely remains 1500.
2
Examine the following C++ program and identify where Class, Object, Encapsulation, Data Abstraction, and Message Passing appear, and trace its exact output.
#include <iostream>
using namespace std;
class Rectangle {
private:
int length, width;
public:
void setDimensions(int l, int w) {
length = (l > 0) ? l : 1;
width = (w > 0) ? w : 1;
}
int area() const {
return length * width;
}
};
int main() {
Rectangle r1, r2;
r1.setDimensions(5, 4);
r2.setDimensions(7, -3);
cout << r1.area() << " " << r2.area() << endl;
return 0;
}Mapping OOP Concepts to Code Constructs:
- Class:
class Rectangle { ... };defines the blueprint with attributes (length,width) and methods (setDimensions,area). - Objects:
r1andr2insidemain()are two independent instances ofRectangle, each with its own memory forlengthandwidth. - Encapsulation: Both data (
length,width) and behaviour (setDimensions,area) are bundled insideRectangle, withprivatehiding the raw fields. - Data Abstraction:
main()simply asksr1.area()without knowing whetherareais stored or computed on demand. - Message Passing:
r1.setDimensions(5, 4)andr2.area()send messages to specific receiver objects (r1,r2).
Tracing the Output:
r1.setDimensions(5, 4): both5 > 0and4 > 0, sor1.length = 5,r1.width = 4.r1.area()returns5 * 4 = 20.r2.setDimensions(7, -3):7 > 0sor2.length = 7, but-3 <= 0triggers the guard, settingr2.width = 1.r2.area()returns7 * 1 = 7.
- Class:
Rectangle; Objects:r1, r2; Encapsulation:privatedata bundled withpublicmethods; Abstraction: callingarea()without internal details; Message Passing:r1.setDimensions(5, 4),r1.area(), etc. - Program output:
20 7
Exercises
Exercises — Introduction to Object Oriented Programming
Explain why Object-Oriented Programming was needed despite the success of Procedure-Oriented Programming. List four major differences between POP and OOP.
Why OOP Was Needed:
- Unprotected Global Data: In POP, shared data must be global so multiple functions can access it, exposing it to accidental modification anywhere in the program.
- Poor Modularity Under Change: Functions depend directly on data layouts; changing a data structure forces edits across many functions.
- Difficulty Modelling Real-World Systems: POP focuses on step-by-step procedures rather than real-world entities that combine state and behaviour.
- Weak Reusability: Extending existing procedural code typically means copying or modifying tested functions rather than inheriting and specializing them.
Four Key Differences (POP vs. OOP):
- Focus: POP focuses on functions/algorithms; OOP focuses on data and objects.
- Design Strategy: POP uses a top-down approach; OOP uses a bottom-up approach.
- Data Security: POP provides no access specifiers to hide data; OOP enforces
private/protected/publicdata hiding. - Reusability & Polymorphism: POP reuses via function calls without overloading; OOP supports inheritance, function/operator overloading, and virtual polymorphism.
OOP addresses POP's exposed global data, tight coupling, weak real-world modelling, and limited reusability. POP is top-down and function-centric without data hiding, whereas OOP is bottom-up and object-centric with encapsulation, inheritance, and polymorphism.
Distinguish between Encapsulation and Data Abstraction with a clear example. How does C++ achieve both?
Distinction:
- Encapsulation is the structural bundling of data members and member functions into a single unit (a class), along with restricting direct access to internal data (
private/protected). It answers "how are data and methods packaged and protected?" - Data Abstraction is the design principle of exposing only essential operations (the public interface) while hiding internal implementation details. It answers "what essential behaviour does the user see?"
How C++ Achieves Both: In C++, placing data members under private: inside a class achieves encapsulation and data hiding, while exposing clean public: member functions (like push(), pop() on a Stack class) provides abstraction—callers use the stack without knowing whether it uses an array or linked list internally.
Encapsulation wraps data and functions together in a class and hides internal state with private; Data Abstraction exposes only essential public operations while hiding implementation details. Both are implemented in C++ classes using private data and public interfaces.
Briefly define the following OOP concepts: (a) Class and Object, (b) Inheritance, (c) Polymorphism, (d) Dynamic Binding, and (e) Message Passing.
Definitions of Core Concepts:
- (a) Class and Object: A class is a user-defined blueprint declaring data members and member functions (occupies no instance memory). An object is a run-time instance of a class with allocated memory.
- (b) Inheritance: The mechanism by which a derived class acquires attributes and methods of a base class, supporting hierarchical classification and reuse.
- (c) Polymorphism: The ability of one function name or operator to exhibit different behaviours depending on parameter types (compile-time) or actual object type (run-time).
Dynamic Binding and Message Passing:
- (d) Dynamic Binding: Resolving which overridden virtual function body to execute at run time based on the actual object type pointed to by a base pointer/reference.
- (e) Message Passing: Communication between objects by invoking a member function on a target object (e.g.,
student.calculateGPA()), specifying receiver, message, and parameters.
A class is a blueprint and an object is its instance; inheritance lets a derived class reuse a base class; polymorphism allows one interface to take many forms; dynamic binding resolves overridden calls at run time; and message passing invokes methods on target objects.
Trace the following C++ code and calculate the total memory size (in bytes) occupied by the three objects s1, s2, and s3 assuming int is 4 bytes, char is 1 byte, and there is no struct padding. Also state what the program prints.
#include <iostream>
using namespace std;
class Sensor {
private:
int id;
char grade;
int reading;
public:
void init(int i, char g, int r) { id = i; grade = g; reading = r; }
int value() const { return reading; }
};
int main() {
Sensor s1, s2, s3;
s1.init(1, 'A', 42);
s2.init(2, 'B', 58);
s3.init(3, 'A', 100);
cout << s1.value() + s2.value() + s3.value() << endl;
return 0;
}Memory Occupied by Objects: Member functions (init, value) are stored once in the program's code segment, not duplicated inside each object. Only non-static data members occupy memory per object:
- Each
Sensorobject contains twointfields (4 + 4 = 8bytes) and onecharfield (1byte), giving4 + 1 + 4 = 9bytes per object (ignoring alignment padding). - For 3 objects (
s1,s2,s3), total data memory is3 * 9 = 27bytes.
Tracing the Output: s1.value() returns 42, s2.value() returns 58, and s3.value() returns 100. Their sum is 42 + 58 + 100 = 200.
Ignoring padding, each object takes 9 bytes (27 bytes total for s1, s2, s3; member functions are shared in code memory). The program prints 200.
Why is C++ considered a hybrid object-oriented language whereas Smalltalk is called a pure object-oriented language? State three advantages and three disadvantages of OOP.
Hybrid vs. Pure OOP:
- C++ (Hybrid): Retains C's procedural constructs—primitive types (
int,double) are not objects, and standalone global functions such asmain()exist outside any class. Programs can mix procedural and OOP styles. - Smalltalk (Pure): Every entity—including numbers, booleans, and control blocks—is an object, and all computation occurs strictly via message passing between objects.
Advantages and Disadvantages:
- Three Advantages: (1) Data security via encapsulation (
privatehiding), (2) code reusability and extensibility via inheritance, (3) modularity and easier maintenance for large systems. - Three Disadvantages: (1) Larger binary/memory footprint, (2) steeper design learning curve, (3) slight run-time overhead (e.g., virtual dispatch) and boilerplate for tiny scripts.
C++ is hybrid because it supports standalone functions and non-object primitives alongside classes, while Smalltalk is pure because everything is an object. OOP improves security, reuse, and modularity, at the cost of larger binaries, steeper design complexity, and minor runtime overhead.