PadhaikoAll subjects

Introduction to Object Oriented Programming

Object Oriented Programming (ENCT 151)

Open in the Padhaiko app

1.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.

Evolution of Programming Languages and Paradigms
Generation / ParadigmRepresentative LanguagesKey CharacteristicsPrimary Limitation
1GL — Machine LanguageBinary opcodes (0s and 1s)Directly executed by CPU; zero translation neededHardware-dependent, extremely error-prone, unreadable
2GL — Assembly Languagex86, 8085 AssemblySymbolic mnemonics (MOV, ADD); translated by an assemblerStill machine-specific; tedious for large applications
3GL — Unstructured / Early High-LevelFORTRAN, COBOL, BASICEnglish-like statements; portable across machinesHeavy reliance on GOTO created tangled "spaghetti code"
Structured / Procedure-Oriented (POP)C, Pascal, ALGOLTop-down decomposition into functions, loops, and blocksData is separated from functions; global data is exposed
Object-Oriented (OOP)Simula 67, Smalltalk, C++, JavaBottom-up design bundling data and methods into objectsLarger design effort and runtime/memory overhead for small tasks

Milestones Leading to C++ and OOP

  1. Simula 67 (1967): Developed by Ole-Johan Dahl and Kristen Nygaard for discrete-event simulation; introduced the foundational ideas of classes and objects.
  2. Smalltalk (1970s): Created at Xerox PARC by Alan Kay and team; established pure OOP where everything is an object communicating by message passing.
  3. 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:

  1. 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.
  2. 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.
  3. 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.
  4. Limited Code Reusability and Extensibility: Extending an existing procedural module often requires modifying tested source code rather than cleanly building upon it.
  5. 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.

AspectProcedure-Oriented Programming (POP)Object-Oriented Programming (OOP)
Primary EmphasisAlgorithms and sequence of actions (doing things)Data and the objects that own it (things being modelled)
Program DivisionDivided into small units called functionsDivided into entities called objects (from classes)
Design ApproachTop-down approachBottom-up approach
Data SecurityGlobal data moves freely and is vulnerable to accidental changeData can be kept private inside an object (data hiding)
Access SpecifiersNo access control (public/private/protected)Explicit access control (private, protected, public)
Overloading & PolymorphismNot supported natively (in C)Function overloading and operator overloading supported
Code Reuse MechanismCalling library functionsInheritance, composition, and templates
Inter-module CommunicationFunction calls passing data argumentsMessage passing between objects
ExamplesC, Pascal, FORTRAN, COBOLC++, 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.

Definition

Class and Object

Definition

Encapsulation and Data Abstraction

Definition

Inheritance, Polymorphism, Dynamic Binding, and Message Passing


1.5 Popular object oriented languages

Object-oriented languages differ in how strictly they enforce OOP and how they execute code:

Popular Object-Oriented Languages
LanguageOOP StyleExecution / TypingNotable Features & Typical Use
C++Hybrid (supports both POP and OOP)Compiled, statically typedDirect hardware/memory control, templates, zero-overhead abstraction; systems, games, embedded
JavaClass-based OOPCompiled to bytecode (JVM), statically typedAutomatic garbage collection, platform independence ("write once, run anywhere"); enterprise, Android
PythonMulti-paradigm (everything is an object)Interpreted, dynamically typedConcise syntax, huge ecosystem; scripting, web backends, data science, AI
C#Class-based OOPCompiled to IL (.NET CLR), statically typedRich properties/events, LINQ; desktop, enterprise web, Unity game development
SmalltalkPure OOPVirtual machine, dynamically typedPioneered MVC architecture and live object environments; every value including integers is an object
Simula 67First OOP languageCompiled, statically typedIntroduced classes, objects, and virtual methods for simulation

1.6 Advantages of OOP

  1. Modularity: Each class forms a self-contained module with clear responsibilities, simplifying debugging and team development.
  2. Reusability: Through inheritance and composition, tested classes can be extended into new classes without rewriting or breaking existing code.
  3. Data Security (Data Hiding): Keeping attributes private protects object invariants from accidental corruption by outside functions.
  4. Extensibility and Maintainability: New object types can be added with minimal changes to existing callers, reducing maintenance costs.
  5. Natural Real-World Mapping: Classes mirror domain entities (e.g., Employee, Invoice, Sensor), making system design easier to understand and verify.
  6. Polymorphic Flexibility: Code written against a base interface works seamlessly with new derived classes added later.

1.7 Disadvantages of OOP

  1. Larger Program Size and Memory Overhead: Class metadata, vtables (for virtual functions), and wrapper code typically make OOP binaries larger than equivalent C programs.
  2. Execution Overhead: Run-time polymorphism (dynamic dispatch) and frequent object creation/destruction can add slight latency in performance-critical tight loops if used carelessly.
  3. Steeper Learning Curve: Designing good class hierarchies requires understanding abstraction, inheritance rules, and object lifetimes, which is harder initially than writing linear functions.
  4. Overkill for Small or Strictly Sequential Tasks: Writing a short utility script or simple mathematical filter in full OOP style can introduce unnecessary boilerplate.
  5. Deep Inheritance Fragility: Poorly planned, overly deep inheritance trees become rigid and hard to refactor.

Worked Examples

Example 1

1 (6 marks)

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:

POP Approach: Unprotected DataC++
#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:

OOP Approach: Protected State in a ClassC++
#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;
}
Answer:

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.

Example 2

2 (5 marks)

Examine the following C++ program and identify where Class, Object, Encapsulation, Data Abstraction, and Message Passing appear, and trace its exact output.

Tracing OOP Concepts in C++C++
#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: r1 and r2 inside main() are two independent instances of Rectangle, each with its own memory for length and width.
  • Encapsulation: Both data (length, width) and behaviour (setDimensions, area) are bundled inside Rectangle, with private hiding the raw fields.
  • Data Abstraction: main() simply asks r1.area() without knowing whether area is stored or computed on demand.
  • Message Passing: r1.setDimensions(5, 4) and r2.area() send messages to specific receiver objects (r1, r2).

Tracing the Output:

  • r1.setDimensions(5, 4): both 5 > 0 and 4 > 0, so r1.length = 5, r1.width = 4. r1.area() returns 5 * 4 = 20.
  • r2.setDimensions(7, -3): 7 > 0 so r2.length = 7, but -3 <= 0 triggers the guard, setting r2.width = 1. r2.area() returns 7 * 1 = 7.
Answer:
  • Class: Rectangle; Objects: r1, r2; Encapsulation: private data bundled with public methods; Abstraction: calling area() without internal details; Message Passing: r1.setDimensions(5, 4), r1.area(), etc.
  • Program output: 20 7

Exercises

Exercises — Introduction to Object Oriented Programming

Question 1

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:

  1. 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.
  2. Poor Modularity Under Change: Functions depend directly on data layouts; changing a data structure forces edits across many functions.
  3. Difficulty Modelling Real-World Systems: POP focuses on step-by-step procedures rather than real-world entities that combine state and behaviour.
  4. 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):

  1. Focus: POP focuses on functions/algorithms; OOP focuses on data and objects.
  2. Design Strategy: POP uses a top-down approach; OOP uses a bottom-up approach.
  3. Data Security: POP provides no access specifiers to hide data; OOP enforces private/protected/public data hiding.
  4. Reusability & Polymorphism: POP reuses via function calls without overloading; OOP supports inheritance, function/operator overloading, and virtual polymorphism.
Answer:

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.

Question 2

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.

Answer:

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.

Question 3

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.
Answer:

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.

Question 4

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.

Class Size and Object State ExerciseC++
#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 Sensor object contains two int fields (4 + 4 = 8 bytes) and one char field (1 byte), giving 4 + 1 + 4 = 9 bytes per object (ignoring alignment padding).
  • For 3 objects (s1, s2, s3), total data memory is 3 * 9 = 27 bytes.

Tracing the Output: s1.value() returns 42, s2.value() returns 58, and s3.value() returns 100. Their sum is 42 + 58 + 100 = 200.

Answer:

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.

Question 5

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 as main() 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 (private hiding), (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.
Answer:

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.

Basics of C++ Programming →