Chapter 5- Object Oriented Programming (OOP)

 



1. Programming Paradigms

A programming paradigm is a style or approach of writing and organizing computer programs. There are three main paradigms: Procedural, Structural and Object-Oriented.

A. Procedural-Oriented Programming (POP)

A program is divided into small parts called functions or procedures.

•       Focuses on functions.

•       Follows a top-down approach.

•       Data is shared among functions (global data).

•       Less data security.

•       Examples: C, Pascal.

B. Structural Programming

A program is divided into small, manageable blocks using three control structures:

•       Sequence – statements execute one after another.

•       Selection – decision making (if, if...else, switch).

•       Iteration – looping (for, while, do...while).

C. Object-Oriented Programming (OOP)

A program is organized using objects and classes. Data and functions are combined into a single unit.

•       Focuses on objects and data.

•       Follows a bottom-up approach.

•       Provides data security through data hiding.

•       Supports code reusability.

•       Examples: C++, Java.

Remember: OOP = Class + Object + Data + Functions.

Comparison of the three paradigms

Point

Procedural

Structural

Object-Oriented

Main focus

Functions

Control structures (sequence, selection, iteration)

Objects and data

Approach

Top-down

Top-down

Bottom-up

Program divided into

Functions / procedures

Blocks / modules

Classes and objects

Data handling

Shared (global) among functions

Mostly shared

Hidden inside objects

Data security

Less

Less

More

Reusability

Limited

Limited

High (inheritance)

Examples

C, Pascal

C, Pascal

C++, Java

2. Features of OOP

The four major features (pillars) of OOP are Encapsulation, Inheritance, Polymorphism and Abstraction.

A. Encapsulation

The process of combining data and functions into a single unit called a class.

•       Example: a Student class contains data (name, roll number) and functions (display details).

•       Advantages: protects data, keeps programs organized, improves security.

B. Inheritance

The process by which one class acquires the properties and functions of another class.

•       Example: a Child class inherits properties from a Parent class.

•       The existing class is the base / parent / super class; the new class is the derived / child / sub class.

•       Advantages: code reusability, less duplication, saves programming time.

C. Polymorphism

Poly = many, morph = forms. One name having many forms. The same function or operator performs different tasks in different situations.

•       Example: the + operator adds two numbers and also joins two strings.

•       Types: compile-time (function and operator overloading) and run-time (function overriding).

•       Advantages: increases flexibility, makes programs easier to extend, allows one interface for different tasks.

D. Abstraction

Hiding unnecessary internal details and showing only the essential information to the user.

•       Example: while driving a car we use the steering wheel and brakes without knowing how they work internally.

•       Advantages: reduces complexity, improves security, makes programs easier to use.

Other important concepts

•       Message passing – objects communicate by sending and receiving information (calling each other's member functions).

•       Dynamic binding – the function to run is decided at run time, not at compile time.

•       Data hiding – internal data is kept private so outside code cannot change it directly.

3. Class and Object

A. Class

A class is a blueprint or template used to create objects. It defines the data members and member functions of the objects.

•       Example: Student is a class containing name, roll number and address.

•       Data members – variables declared inside a class.

•       Member functions – functions declared inside a class.

B. Object

An object is an instance of a class. It represents a real-world entity and has its own data and behaviour.

•       Example: Raju and Sita are objects of the Student class.

•       Every object has state (data), behaviour (functions) and identity (its own name/address).

Difference between Class and Object

Class

Object

It is a blueprint.

It is an instance of a class.

It is a logical entity.

It is a physical entity.

It defines properties and functions.

It uses those properties and functions.

Memory is not allocated for ordinary non-static instance data just by defining a class.

Memory is allocated when an object is created.

A class is declared once.

Many objects can be created from one class.

Example: Student

Example: Raju, Sita

4. Data Hiding, Constructor and Destructor

A. Data hiding and access specifiers

Data hiding restricts direct access to the internal data of a class. It protects data from unauthorized access and modification. In C++, access specifiers are used for data hiding.

Specifier

Who can access the members

public

Anywhere: inside the class, derived classes and outside the class.

private

Only inside the class and its friends (default for a class).

protected

Inside the class and its derived classes.

B. Constructor

A constructor is a special member function that is called automatically when an object is created. It is used to initialize the data members.

•       Has the same name as the class.

•       Has no return type (not even void).

•       Declared in the public section (usually).

•       Can be overloaded.

Types of constructors

1.      Default constructor – takes no arguments.

2.      Parameterized constructor – takes arguments to initialize with given values.

3.      Copy constructor – creates a new object as a copy of an existing object.

A destructor is a special member function that is called automatically when an object is destroyed. It releases the resources (memory) used by the object.

•       Has the same name as the class, preceded by a tilde ~.

•       Has no return type, takes no arguments, and cannot be overloaded.

•       Only one destructor per class.

Difference between Constructor and Destructor

Constructor

Destructor

Initializes the object.

Destroys the object and frees memory.

Called when the object is created.

Called when the object goes out of scope or is deleted.

Name is the same as the class name.

Name is the class name with ~ in front.

Can take arguments.

Cannot take arguments.

Can be overloaded.

Cannot be overloaded.

A class can have many constructors.

A class has only one destructor.

5. Types of Polymorphism

A. Compile-time polymorphism (early binding)

The function to be executed is determined during compilation.

•       Function overloading – same function name with different parameters.

•       Operator overloading – giving an existing operator an extra meaning for user-defined types.

int add(int a, int b)        { return a + b; }
int add(int a, int b, int c) { return a + b + c; }
double add(double a, double b) { return a + b; }

B. Run-time polymorphism (late binding)

The function to be executed is determined while the program is running.

•       Function overriding – a child class redefines a parent class function.

•       Implemented using virtual functions and base-class pointers.

class Animal {
  public:
    virtual void sound() { cout << "Animal sound"; }
};
class Dog : public Animal {
  public:
    void sound() { cout << "Bark"; }   // overrides Animal::sound()
};

A virtual function is a member function of the base class that is redefined in the derived class and is resolved at run time.

Difference between Overloading and Overriding

Overloading

Overriding

Same function name with different parameters.

Child class redefines a parent class function.

Usually occurs in the same class.

Occurs between parent and child classes.

Example: add(int, int), add(int, int, int).

Parent and child have the same function signature.

Compile-time polymorphism.

Run-time polymorphism when implemented using virtual functions.

Difference between Compile-time and Run-time Polymorphism

Compile-time polymorphism

Run-time polymorphism

Function call is resolved at compile time.

Function call is resolved at run time.

Also called early or static binding.

Also called late or dynamic binding.

Achieved by function and operator overloading.

Achieved by function overriding with virtual functions.

Faster execution.

Slightly slower execution.

Occurs within one class.

Needs inheritance (parent and child classes).

6. Types of Inheritance

Inheritance is classified into five types.

Type

Meaning

Pattern (A, B, C = classes)

Single

One child class inherits from one parent class.

A → B

Multiple

One child class inherits from two or more parent classes.

A, B → C

Multilevel

A class inherits from another derived class.

A → B → C

Hierarchical

Multiple child classes inherit from one parent class.

A → B, A → C

Hybrid

Combination of two or more types of inheritance.

e.g. multilevel + multiple

7. Advantages, Disadvantages and Applications of OOP

Advantages

1.      Code reusability – existing code can be reused through inheritance.

2.      Data security – data is protected from unauthorized access.

3.      Easy maintenance – programs can be modified and maintained easily.

4.      Flexibility – polymorphism gives flexibility.

5.      Modularity – programs are divided into separate classes and objects.

6.      Reduced complexity – large programs are divided into smaller parts.

7.      Real-world modelling – objects represent real-world entities.

Disadvantages

1.      OOP programs can be more complex to design.

2.      Requires more memory in some situations.

3.      Takes more time to learn and understand.

4.      Not suitable for every small or simple program.

5.      Program execution can have additional overhead.

Applications

Field

Use

Game development

Developing computer and mobile games.

Web development

Developing websites and web applications.

Mobile applications

Creating Android and other mobile apps.

Banking systems

Managing customer accounts and transactions.

Educational software

Developing student management systems.

Simulation

Simulating real-world objects and situations.

Other

Operating systems, CAD/CAM, databases, AI and expert systems.

8. Difference between POP and OOP (frequently asked – 5 marks)

POP

OOP

Stands for Procedural Oriented Programming.

Stands for Object Oriented Programming.

Focuses on functions.

Focuses on objects.

Follows top-down approach.

Follows bottom-up approach.

Data is generally shared among functions.

Data is protected through data hiding.

Less secure.

More secure.

Code reusability is limited.

Supports code reusability through inheritance.

Program is divided into functions.

Program is divided into classes and objects.

Example: C, Pascal.

Example: C++, Java.

Difference between Encapsulation and Abstraction

Encapsulation

Abstraction

Combines data and functions into one unit.

Hides unnecessary internal details.

Focuses on data protection and organization.

Focuses on simplicity.

Achieved using classes and access control.

Achieved using interfaces and abstract classes, among other techniques.

Works at the implementation level.

Works at the design level.

Example: Student class.

Example: Driving a car without knowing its internal mechanism.

Difference between Structure and Class

Structure

Class

Members are public by default.

Members are private by default.

Mainly groups data.

Groups data and functions with access control.

Does not support data hiding by default.

Supports data hiding.

Declared with the struct keyword.

Declared with the class keyword.

Difference between Function Overloading and Operator Overloading

Function Overloading

Operator Overloading

Same function name with different parameters.

Gives an operator a new meaning for user-defined types.

Example: add(int, int) and add(float, float).

Example: + used to add two objects.

Uses function names.

Uses the operator keyword.

 

Book exercise page number 249

1. Multiple Choice Questions

i. What is encapsulation in object-oriented programming?

a. A process of converting objects into data.

b. A way to hide the implementation details and expose only necessary functionalities. ✔

c. A technique to create copies of objects.

d. A process of organizing data into classes and objects.

 

ii. Which OOP principle states that a subclass can inherit attributes and behaviors from a superclass?

a. Polymorphism

b. Abstraction

c. Encapsulation

d. Inheritance✔

 

iii. Which term describes the ability of an object to take on many forms?

a. Polymorphism✔

b. Encapsulation

c. Abstraction

d. Inheritance

 

iv. In object-oriented programming, what is a constructor?

a. A method that is called when an object is deleted.

b. A method used to define the public interface of a class.

c. A method that is used to access private data members of a class.

d. A special method used to initialize objects and set their initial state. ✔

 

v. What is the purpose of the "super" keyword in many object-oriented programming languages?

a. It refers to the current object being worked on.

b. It is used to call the superclass constructor. ✔

c. It is a keyword reserved for naming classes.

d. It is used to declare static methods.

 

vi. What is the main advantage of using inheritance in object-oriented programming?

a. It allows for the creation of multiple instances of an object.

b. It ensures that objects cannot be modified after they are created.

c. It allows new classes to reuse properties and behaviors of existing classes. ✔

d. It simplifies the process of garbage collection.

 

vii. Which concept in OOP allows a class to inherit properties and behaviors from multiple parent classes?

a. Encapsulation

b. Overloading

c. Polymorphism

d. Multiple Inheritance✔

 

viii. What is a "method overriding" in OOP?

i. The process of creating a new method in a subclass with the same name as a method in the superclass.

ii. The process of creating a copy of an existing method in a class.

iii. The process of creating a method that can take multiple forms.

iv. The process of defining a method in a subclass that has the same name and signature as a method in the superclass. ✔

 

ix. In OOP, what is a "class"?

a. A concrete instance of an object.

b. A blueprint or template for creating objects. ✔

c. A method that is inherited from a parent class.

d. A variable that holds the data of an object.

 

2. Short Answer Questions

i. List the advantages and disadvantages of the structured programming approach.

Structured programming builds a program from sequence, selection (if/switch) and iteration (loops), with no unrestricted goto.

Advantages:

  • Programs are easy to read, understand and debug.
  • Large problems are split into small modules or functions.
  • Modules can be reused and tested separately.
  • Maintenance and modification are easier.
  • Several programmers can work on different modules.

Disadvantages:

  • Data is global and not protected, so any function can change it.
  • It does not model real-world objects well.
  • Large programs become hard to manage and change.
  • Reuse of code across projects is limited compared with OOP.
  • A change in a data structure can force changes in many functions.

ii. What is inheritance? Write its types.

Inheritance is the OOP feature by which a new class (derived or child class) acquires the properties and behaviors of an existing class (base or parent class). It supports code reuse and lets the child class add or modify features.

Types of inheritance:

  1. Single inheritance: one derived class from one base class (B inherits A).
  2. Multiple inheritance: one derived class from two or more base classes (C inherits A and B).
  3. Multilevel inheritance: a chain of classes (C inherits B, which inherits A).
  4. Hierarchical inheritance: several derived classes from one base class (B and C inherit A).
  5. Hybrid inheritance: a combination of two or more of the above types.

iii. What is polymorphism? Write its example.

Polymorphism means "many forms". It is the ability of the same function name or operator to behave differently depending on the context. In C++ it appears as compile-time polymorphism (function overloading, operator overloading) and run-time polymorphism (virtual functions and overriding).

Example (function overloading):

#include <iostream>
using namespace std;
 
class Area {
public:
    int calc(int s)           { return s * s; }        // square
    int calc(int l, int b)    { return l * b; }        // rectangle
    float calc(float r)       { return 3.14f * r * r; }// circle
};
 
int main() {
    Area a;
    cout << a.calc(4) << endl;      // 16
    cout << a.calc(4, 5) << endl;   // 20
    cout << a.calc(2.0f) << endl;   // 12.56
    return 0;
}

The function calc has one name but three forms, chosen by the arguments.

iv. Write the advantages and disadvantages of procedural programming.

Advantages:

  • Simple and easy to learn and follow.
  • Code is reusable because a function can be called many times.
  • Programs are modular, so debugging and testing are easier.
  • It runs efficiently with low memory use.
  • Suitable for small and medium programs.

Disadvantages:

  • Data is exposed and can be changed by any function (no data hiding).
  • It does not model real-world entities well.
  • It is hard to maintain and extend for large, complex programs.
  • A change to shared data can affect many functions.
  • No inheritance or polymorphism, so reuse is limited.

v. What are the features of procedural programming?

  • Program is divided into procedures (functions or subroutines).
  • Top-down approach: the main problem is broken into smaller tasks.
  • Emphasis is on procedures and the steps (algorithm), not on data.
  • Uses sequence, selection and iteration control structures.
  • Data is usually global and shared between functions; local variables are also used.
  • Functions can be reused by calling them repeatedly.
  • Data moves between functions through parameters and return values.
  • Examples: C, Pascal, FORTRAN, COBOL.

3. Long Answer Questions

i. Why is C++ called an object-oriented programming language? Explain.

C++ is called object-oriented because it supports the four main OOP concepts and lets a program be built from objects that combine data and the functions working on that data. (It also supports procedural style, so it is often called a hybrid language.) Its OOP features are:

  1. Class and object: a class is a blueprint that groups data members and member functions; an object is an instance of a class.
  2. Encapsulation: data and functions are wrapped in one unit (the class). Access specifiers private, protected and public hide data and expose only a public interface.
  3. Abstraction: only essential details are shown to the user and implementation is hidden, for example through classes, abstract classes and header interfaces.
  4. Inheritance: a derived class reuses and extends a base class (single, multiple, multilevel, hierarchical, hybrid).
  5. Polymorphism: one name, many forms, through function overloading, operator overloading (compile time) and virtual functions (run time).
  6. Constructors and destructors: special member functions that initialize and clean up objects automatically.

Example:

class Student {
private:
    int roll;                      // hidden data
public:
    Student(int r) { roll = r; }   // constructor
    void show() { cout << roll; }  // public interface
};

Because C++ provides all of these features and models real-world entities as objects, it is an object-oriented language.

ii. What are the differences between C and C++?

Basis

C

C++

Paradigm

Procedural (structured)

Multi-paradigm: procedural and object-oriented

Approach

Top-down

Bottom-up

Focus

Functions and procedures

Objects and data

Data hiding

Not supported; data is exposed

Supported through private and protected

Classes and objects

Not supported (only struct without functions)

Supported

Inheritance and polymorphism

Not supported

Supported

Function overloading

Not allowed

Allowed

Operator overloading

Not allowed

Allowed

Input/output

scanf() and printf()

cin and cout

Memory allocation

malloc() and free()

new and delete operators

Reference variables

Not available

Available

Namespaces and exceptions

Not available

namespace, try/catch/throw

Header files

<stdio.h>

<iostream>

Origin

Dennis Ritchie, 1972

Bjarne Stroustrup, 1979 (first called "C with Classes")

iii. What are the differences between procedural programming and object-oriented programming?

Basis

Procedural Programming

Object-Oriented Programming

Main unit

Functions (procedures)

Objects and classes

Approach

Top-down

Bottom-up

Focus

Procedures, with data kept separate

Data, with data and functions bound together

Data security

Low; global data is open to all functions

High; data hiding through encapsulation

Real-world modelling

Difficult

Easy and natural

Inheritance

Not supported

Supported

Polymorphism

Not supported

Supported

Code reuse

By calling functions

By inheritance and classes

Best suited for

Small and medium programs

Large and complex programs

Maintenance

Harder as the program grows

Easier

Examples

C, Pascal, FORTRAN

C++, Java, Python, C#

iv. What is procedural programming? Explain its merits and demerits.

Procedural programming is a paradigm in which a program is written as a sequence of instructions grouped into procedures (functions or subroutines). Each procedure does one task and may be called from anywhere in the program. The problem is solved top-down by breaking it into smaller procedures, and the main focus is on the steps (algorithm) rather than the data. Languages such as C, Pascal, FORTRAN and COBOL follow this style.

Merits:

  • Simple and easy to learn and understand.
  • Modularity: the program is divided into functions, so it is easy to debug and test.
  • Reusability: a function is written once and called many times.
  • Efficient execution with low memory use, so it suits small and system-level programs.
  • Easy to trace the flow of control from top to bottom.

Demerits:

  • Data is global and unprotected, so any function can change it by mistake.
  • Real-world problems are hard to model because there are no objects.
  • Large programs become complex and hard to maintain or extend.
  • A change in data structure forces changes in all functions using it.
  • Limited code reuse because it lacks inheritance and polymorphism.