1 Object Oriented Programming Fundamentals

Object Oriented Programming · Unit 1

Object-Oriented Programming Fundamentals

Exam-focused notes for Object-Oriented Programming Fundamentals (Object Oriented Programming, BIT153): what the TU syllabus asks and how it has actually been tested, with 6 solved past questions from this unit.

Object-Oriented Programming Fundamentals in short

Object-oriented programming (OOP) builds a program from objects that hold data and the functions that work on that data. It helps us write large programs that are easier to reuse, change and maintain. This subject uses C++.

Object-Oriented Programming Fundamentals: notes

OOP definition and concepts

Object-oriented programming is a style of programming where the program is organised as a set of objects. Each object combines data (its properties) with functions (its behaviour). Objects talk to each other by calling functions.

The main concepts of OOP are:

  • Class: a blueprint that describes the data and functions of a kind of object.
  • Object: a real instance of a class that takes up memory.
  • Encapsulation: binding data and functions together in one unit.
  • Data abstraction: showing only the needed details and hiding the rest.
  • Inheritance: a new class gets the features of an existing class.
  • Polymorphism: one name, many forms. The same function or operator behaves differently in different cases.
  • Message passing: objects communicate by calling each other's member functions.

Differences between OOP and procedural programming

In procedural programming (like C) the program is a list of procedures or functions. Data is usually global and shared. In OOP, data and functions are kept together inside objects.

Procedural programmingObject-oriented programming
Focus is on functions (procedures)Focus is on data (objects)
Uses top-down approachUses bottom-up approach
Data is global and can be changed by any functionData is hidden inside objects and protected
No real data hidingData hiding through access specifiers
Adding new data is hardNew objects and data are easy to add
Little code reuseCode reuse through inheritance
Examples: C, PascalExamples: C++, Java

What this unit covers

  • OOP definition and concepts
  • Differences between OOP and procedural programming
  • Features of object-oriented programming
  • Bottom-up approach in OOP
  • Classes and objects
  • Structures versus classes

Structures versus classes

2081 · 10 marks

How does structure differ with class?What are the uses of friend function and friend class?Explain the types of constructors.[1+3+6]

Show solved answer

Structure vs Class, Friend Functions/Classes, and Types of Constructors


1. How does Structure differ with Class?

In C++, struct and class are almost identical, with one key difference:

FeatureStructure (struct)Class (class)
Default access specifierPublicPrivate
Default inheritancePublicPrivate
General useSimple data groupingFull OOP with data hiding

Example:

struct S { int x; };   // x is public by default
class C { int x; };    // x is private by default

In C++, a struct can also have member functions, constructors, and inheritance, just like a class.


2. Uses of Friend Function and Friend Class

Friend Function

A friend function is a non-member function that is granted access to the private and protected members of a class by declaring it with the keyword friend inside the class.

Uses:

  • To allow an external function to access private data of a class
  • Useful for operator overloading (e.g., <<, >>)
  • To allow two classes to share data without making members public

Syntax:

class Box {
    private:
        int length;
    public:
        Box(int l) { length = l; }
        friend void showLength(Box b);  // friend declaration
};

void showLength(Box b) {
    cout << "Length: " << b.length;    // accesses private member
}

Friend Class

A friend class is a class that is granted access to the private and protected members of another class.

Uses:

  • When two closely related classes need to share private data
  • Useful in implementing container and iterator relationships

Syntax:

class Engine {
    private:
        int horsepower;
    public:
        Engine(int hp) { horsepower = hp; }
        friend class Car;   // Car is a friend of Engine
};

class Car {
    public:
        void show(Engine e) {
            cout << "HP: " << e.horsepower;  // accesses private member
        }
};

Note: Friendship is not inherited and not mutual (if A is a friend of B, B is not automatically a friend of A).


3. Types of Constructors

A constructor is a special member function that has the same name as the class, has no return type, and is automatically called when an object is created. It is used to initialize objects.


Type 1: Default Constructor

A constructor that takes no arguments (or all arguments have default values).

  • Automatically provided by the compiler if no constructor is defined
  • Called when an object is created without any arguments
class Student {
    public:
        int roll;
        string name;

        Student() {           // Default constructor
            roll = 0;
            name = "Unknown";
        }
};

int main() {
    Student s;   // Default constructor called
}

Type 2: Parameterized Constructor

A constructor that accepts one or more arguments to initialize an object with specific values.

  • Allows different objects to be initialized with different values
  • Supports constructor overloading
class Student {
    public:
        int roll;
        string name;

        Student(int r, string n) {    // Parameterized constructor
            roll = r;
            name = n;
        }
};

int main() {
    Student s1(1, "Ram");
    Student s2(2, "Sita");
}

Type 3: Copy Constructor

A constructor that creates a new object as a copy of an existing object. It takes a reference to an object of the same class as its parameter.

  • Called when an object is initialized from another object
  • Called when an object is passed by value to a function
  • Called when an object is returned by value from a function
class Student {
    public:
        int roll;
        string name;

        Student(int r, string n) {
            roll = r;
            name = n;
        }

        Student(const Student &s) {   // Copy constructor
            roll = s.roll;
            name = s.name;
        }
};

int main() {
    Student s1(1, "Ram");
    Student s2(s1);    // Copy constructor called
    Student s3 = s1;   // Copy constructor called
}

Summary Table

TypeArgumentsPurpose
Default ConstructorNoneInitializes object with default values
Parameterized ConstructorOne or moreInitializes object with given values
Copy ConstructorReference to same class objectCreates a copy of an existing object

Key Points:

  • A class can have multiple constructors (overloading)
  • Constructors cannot be inherited but a derived class can call the base class constructor
  • If any constructor is defined, the compiler does not provide a default constructor automatically
Open this answer on its own page →

2079 · 5 marks

Can we use object oriented concept using structure instead of classes? Justify your opinion. [5]

Yes, , to a significant extent, we can use object-oriented concepts using structures (struct) instead of classes. However, there are important limitations. Below is a justified explanation. --- In C++, a struct and a class are almost identical. The only default difference is access specifier: Fea...

Open this answer on its own page →

Features of object-oriented programming

2081 · 5 marks

Describe the features of object oriented programming. [5]

Note: No specific reference notes were found for this topic. The following answer is based on standard, well-established OOP concepts as taught in BSc CSIT curriculum. --- Object Oriented Programming (OOP) is a programming paradigm that organizes software design around data (objects) rather than ...

Open this answer on its own page →

2079 · 5 marks

Explain the features of OOP. [5]

Object-Oriented Programming (OOP) is a programming paradigm that organizes software design around objects rather than functions and logic. The key features of OOP are: --- - The process of wrapping data (attributes) and methods (functions) together into a single unit called a class. - It hides th...

Open this answer on its own page →

OOP definition and concepts

2078 · 10 marks

What is object-oriented programming? How does it differ from procedure-oriented programming? Explain features of object oriented programming.[10]

Show solved answer

Object-Oriented Programming: Concepts, Comparison, and Features


1. What is Object-Oriented Programming (OOP)?

Object-Oriented Programming (OOP) is a programming paradigm that organizes software design around objects rather than functions and logic. An object is a self-contained unit that bundles together data (attributes) and behavior (methods/functions) that operate on that data.

In OOP, real-world entities are modeled as objects. For example, a "Car" object has attributes like color, speed, and model, and behaviors like start(), stop(), and accelerate().

Key idea:

"OOP treats data as a critical element and does not allow it to flow freely around the system. It ties data more closely to the functions that operate on it."


2. Procedure-Oriented Programming (POP) vs Object-Oriented Programming (OOP)

Procedure-Oriented Programming (POP)

  • Programs are divided into functions/procedures.
  • Focus is on what to do (the logic/algorithm).
  • Data is shared globally and can be accessed by any function.
  • Examples: C, Pascal, FORTRAN.

Comparison Table

FeatureProcedure-Oriented (POP)Object-Oriented (OOP)
Basic UnitFunction / ProcedureObject
FocusAlgorithm / LogicData
Data AccessData is global, freely accessibleData is hidden (encapsulated)
ApproachTop-downBottom-up
Data SecurityLess secure (no data hiding)More secure (data hiding)
Code ReusabilityLimited (functions can be reused)High (via inheritance)
Real-world modelingDifficultNatural and easy
MaintenanceHarder for large programsEasier due to modularity
ExamplesC, Pascal, FORTRANC++, Java, Python

Diagram: Data Flow Comparison

POP:                          OOP:
  Function1                    [Object 1]
  Function2   <-- Global -->   [Object 2]   <-- Message Passing -->
  Function3       Data         [Object 3]

In POP, data flows freely between functions. In OOP, objects communicate through message passing, keeping data protected.


3. Features of Object-Oriented Programming

3.1 Class

  • A class is a blueprint or template for creating objects.
  • It defines the attributes (data members) and behaviors (member functions) that objects of that class will have.
  • Example: class Student { string name; int roll; void display(); };

3.2 Object

  • An object is an instance of a class.
  • It is the actual entity created from the class blueprint that occupies memory.
  • Example: Student s1; -- here s1 is an object of class Student.

3.3 Encapsulation

  • Encapsulation is the mechanism of wrapping data and functions together into a single unit (class).
  • It restricts direct access to some components, protecting the internal state of an object.
  • Achieved using access specifiers: private, protected, public.
  • Benefit: Prevents accidental modification of data (data hiding).
+-----------------------------+
|         Class: BankAccount  |
|-----------------------------|
| - balance (private)         |  <-- Data hidden
|-----------------------------|
| + deposit()  (public)       |  <-- Accessible methods
| + withdraw() (public)       |
+-----------------------------+

3.4 Abstraction

  • Abstraction means showing only the essential features of an object and hiding the unnecessary implementation details.
  • It reduces complexity and allows the programmer to focus on what an object does rather than how it does it.
  • Example: When you call car.start(), you don't need to know the internal combustion mechanism.
  • Achieved through abstract classes and interfaces.

3.5 Inheritance

  • Inheritance is the mechanism by which one class (child/derived class) acquires the properties and behaviors of another class (parent/base class).
  • Promotes code reusability and establishes an "is-a" relationship.

Types of Inheritance:

TypeDescription
SingleOne child inherits from one parent
MultipleOne child inherits from multiple parents
MultilevelChain of inheritance (A -> B -> C)
HierarchicalMultiple children from one parent
HybridCombination of above types
        Animal (Base Class)
           /        \
         Dog         Cat   (Derived Classes)

3.6 Polymorphism

  • Polymorphism means "many forms". It allows the same function or operator to behave differently based on the context.
  • It enables one interface to be used for a general class of actions.

Two types:

TypeDescriptionExample
Compile-time (Static)Resolved at compile timeFunction overloading, Operator overloading
Run-time (Dynamic)Resolved at run timeFunction overriding (virtual functions)

Example:

// Function Overloading (Compile-time)
int add(int a, int b)       { return a + b; }
float add(float a, float b) { return a + b; }

3.7 Message Passing

  • Objects communicate with each other by sending and receiving messages (calling methods).
  • A message specifies the name of the object, the method to invoke, and any parameters needed.
  • Example: s1.display(); -- object s1 receives the message to execute display().

3.8 Dynamic Binding

  • Dynamic Binding (also called late binding) means the code to be executed in response to a function call is determined at runtime, not at compile time
Open this answer on its own page →

Bottom-up approach in OOP

2080.1 · 10 marks

Why object oriented programming is known as bottom up approach?Explain different features of object oriented programming.[3+7]

--- Object Oriented Programming (OOP) is known as a bottom-up approach because the program design starts from the lower level (individual objects/classes) and builds upward toward the complete system. The reasoning is as follows: - In OOP, the programmer first identifies and designs individual ob...

Open this answer on its own page →