0% found this document useful (0 votes)
5 views19 pages

Key Concepts of Object-Oriented Programming

The document outlines key concepts in object-oriented programming (OOP) including objects, classes, functions, methods, and access modifiers, detailing their definitions and roles. It explains OOP principles such as encapsulation, inheritance, polymorphism, and abstraction, along with their implementations in C++. Additionally, it covers memory management, constructors, destructors, shallow and deep copies, and the use of friend functions/classes.

Uploaded by

examscap
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views19 pages

Key Concepts of Object-Oriented Programming

The document outlines key concepts in object-oriented programming (OOP) including objects, classes, functions, methods, and access modifiers, detailing their definitions and roles. It explains OOP principles such as encapsulation, inheritance, polymorphism, and abstraction, along with their implementations in C++. Additionally, it covers memory management, constructors, destructors, shallow and deep copies, and the use of friend functions/classes.

Uploaded by

examscap
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Important Terms

1) Objects
-It is an instance of a class.
-When a class is defined, no memory is allocated until an object of that class is created.
-An object has a state (data stored in its attributes) and behavior (methods).

2) Classes
-It is a user defined blueprint or prototype from which objects are created.
-It represents a set of properties or methods that are common to all objects of one type.
-It is a logical entity that encapsulates data (attributes) and behavior (methods).
3) Functions
-It is a self-contained block of code that performs a specific task.
-It is defined outside of a class and is called independently.
-It may or may not take parameters and may or may not return a value.
-It is not tied to any object or class.

4) Methods
-It is a function that is defined inside a class and describes the behavior or actions that an
object of the class can perform.
-It operates on the data (attributes) of the object it belongs to.
-It is always associated with an object/instance of a class.
Analogies:
-The class is the architect’s blueprint for a model of a house.
-Each object is an actual physical house built from that blueprint (123 Main St, 435 Oak Ave).

-A method is an action specific to a house, like [Link]().


-A function is a public service, like callFireDepartment (), which isn’t tied to any one house.

Access Modifiers
-They are keywords in object-oriented languages that set the accessibility (visibility) of
classes, methods, and other members.
-They are fundamental to implementing encapsulation.
Types:
1) Public
-The member is accessible from anywhere.
-Other classes and object can freely access it.
-Like a public park.
2) private
-The member is accessible only within the class where it’s declared.
-Not even subclasses can access it.
-Like your personal diary – only you can read and write in it. Others can’t access it directly.
3) protected
-The member is accessible within its own class and by derived classes (subclasses), but not
by other classes.
-Like Family secrets – accessible to family members (base and derived classes) but not to
outsiders.

Default:
>class members are private by default.
>struct members are public by default.
Q: Why make members private if we provide public getter/setter?
-Making members private even with public getter/setters isn’t about hiding the data, it’s
about controlling access to it.
-It allows the class to enforce its own rules (validation)[like don’t taking -ve age], change its
internal implementation without breaking other code[like from directly taking full name to
taking first name and last name], and perform necessary actions when data changes[setting
notification like when age changes inform others].
-It turns a simple variable into a managed property with well-defined behavior.

OOP Principles
OOP is a programming paradigm that organizes software design around objects rather than
functions and logic.
A style, methodology, or way of designing and structuring code.
It makes codes more:
1) Modular (easy to isolate and fix parts)
2) Reusable (easy to use objects in different programs)
3) Scalable (easier to manage and grow large, complex applications)
4) Maintainable (easier to understand and update)
C++ supports 4 main OOP principle:

1) Encapsulation (Gift Wrap)


Definition: (Bundling and restricting access)
Bundling data and methods that operate on that data within a single unit (class), while
restricting direct access to some components.
C++ Implementation:
Using private/protected access specifiers and providing public getter/setter methods.
Analogy:
A vending machine – You don’t need to know its internal mechanisms (how it stores
products, calculates change), you just use the public interface (buttons) to interact with it.
Use case: To protect an object’s internal state from invalid or unintended changes by
controlling access to its data.
How it provides data security and prevents unauthorized access:
Through access specifiers.

2) Inheritance (Family Tree)


Definition:
Creating new classes (derived) from existing classes (base), inheriting their properties and
behaviors.
C++ Implementation:
Using (:) syntax and access specifiers (public, protected, private)
Analogy:
Genetic Inheritance – A child inherits traits from parents but can also have unique
characteristics. A “Sportscar” inherits from “Car” but has additional features like turbo
boost.
Use Case:
-Code Reusability.
Different Types of inheritance and their uses:
1) Single Inheritance
2) Multi-level Inheritance (tree)
3) Multiple Inheritance (mixing)
4) Hierarchical Inheritance (binary tree)
5) Hybrid
Q: What is the diamond problem?
It’s an ambiguity that arises in multiple inheritance when a class inherits from two classes
that both inherit from a common base class. This results in the derived class containing
multiple copies of the base class, making references to base class members ambiguous.
Q: How to solve diamond problem?
We use virtual (it also adds overhead and complexity) inheritance. By inheriting from the
common base class using the virtual keyword (class B: virtual public A), you ensure that only
one instance of the base class is present in the derived class, eliminating the ambiguity.

3) Polymorphism (Different Faces)


Definition:
The ability of objects of different classes to respond to the same message (method call) in
different ways.
Compile Time (Static) -> Overloading (Class) -> parameters
Run-Time (Dynamic) -> Overriding (Inheritance) -> depends on whose object created

Analogy:
A remote control – Same power button (interface) turns on different devices (TV, AC, Music
System) in different ways.
Use case: To process objects of different types through a single, uniform interface4)

Abstraction (Complexity)
Definition:
Hiding complex implementation details and showing only essential features.
It’s implemented primarily through Abstract Classes and interfaces.
C++ Implementation:
1) Using abstract classes with pure virtual functions

>Concrete class implements the abstraction.


>Must provide implementation for the pure virtual function.
>Can’t instantiate abstract class.
>They are meant to be inherited.
2) Using Interfaces (Special case of abstract classes)
>It is implemented as an abstract class that contains only pure virtual functions. No data
member and no implemented functions.
3) Using access specifiers (public vs private)
The user doesn’t need to know the sequence of operations.
4) Using Header files (.h) and Implementation Files (.cpp)
>This is a physical, file-level abstraction.
>The header file (.h) declares the class’s public interface (the abstraction), while the
implementation file (.cpp) contains the hidden implementation details.

Analogy:
A car dashboard – You see speed, fuel level (essential info) but not the complex engine
workings (hidden implementation).
Use case: To hide complex implementation details and expose only the essential features of
an object.
Q: Difference between Abstraction and Encapsulation:
Encapsulation: How will I hide the internal state?
Abstraction: What should be hidden to simply the interface?
Encapsulation is like a pill capsule. It bundles medicine (data) inside a shell (the class),
protecting it from the outside environment.
Abstraction is the concept of medicine itself. You know a pill reduces fever (what it does),
but you don’t need to know the complex chemical reactions (how it does it.)

Constructor
It is a special member function that is automatically called when an object is created.
Its primary job is to initialize the object and put it into a valid, ready-to-use state.
Key Properties
1) Same name as the class
2) No return type, not even void.
3) Can be overloaded (different parameters).
Destructor
Special member function that is automatically called when an object is destroyed.
Its primary job is to release resources the object may have acquired during its lifetime.
Key Properties
1) Name as class name with prefix ~.
2) No return type, no parameter.
3) Cannot be overloaded (only one destructor per class).
Why needed?
1) Constructors ensures an object is never in an undefined state.
2) Preventing Resource Leaks – Memory leaks, File handle leaks, database connection leaks,
deadlocks
Q: When and why to create virtual destructor?
When we are dealing with polymorphism (if we have other virtual functions and plan to
delete derived objects through a base class pointer).
Why because if it’s not then, only the base class destructor will be called when deleting a
derived object via a base pointer, leading to resource leaks in derived class.

Q: If we don't want to delete derived objects through a base class pointer, then do we
need a virtual destructor?
-No, the only reason to make a base class destructor virtual is to ensure the correct
destruction sequence when you delete a derived class object via a pointer to the base class.
-The overhead of a virtual destructor (the vtable pointer in each object) can be avoided.
Q: If the compiler guarantees a destructor will run, why we studying it then?
Because it doesn’t know how to release resources like dynamic memory, file handles, or
network sockets that the class may have acquired. Therefore, writing a destructor is
essential for implementing the RAII (Resource Acquisition Is Initialisation) pattern and
preventing resource leaks.
Q: What will happen if we make destructor private?
-It prevents the normal means of destroying an object, like going out of scope or being
deleted directly.
-This is a deliberate technique used in design patterns like Singleton or Object Pool to force
users to destroy objects through a specific, controlled interfaced.
-This gives the class complete control over its own lifecycle and prevents accidental misuse.
this keyword: this-> is used to state that the given variable is for constructor.

Shallow Copy
-It copies all the member values from one object to another.
-If the member is a pointer, it copies the pointer itself, not the data it points to.
-This results in both objects pointing to the same memory location.
-Analogy: Making a photocopy of a document that has your home address written on it.
Both the original and the copy have the same address written on them. They both point to
the same, single house. If the house is painted a new color, both documents now “point” to
the updated house.
-What it leads to: Multiple objects sharing the same resource.
-Problem: It will run two times and if changes happen in first time, then it might show error
on second time.

Deep Copy
-It copies all member values, and for any pointer members, it allocates new memory and
then copies the contents from the original object’s memory to the new location.
-This results in two completely independent objects.
-Analogy: Making a photocopy of the address document, then building an identical,
completely new house at a different address and writing that new address on the copy. Now
you have two identical houses. Painting one house does not affect the other.
-What it leads to: Each object has its own independent copy of the resource.

>Rule of 3
If you need to explicitly define either a destructor, a copy constructor, or a copy assignment
operator, then you likely need to explicitly define all three.
Compile Time Memory Allocation (Static Memory)
Definition:
Memory is allocated for variables at compile time. The size and lifetime of these variables
are determined before the program even runs.
How it works:
The compiler reads your variable declarations and reserves a fixed amount of memory for
them in the program’s stack (local and function parameters) or data segment (global and
static variables).
Key Characteristics:
-Very fast.
-Lifetime tied to scope of variable. Automatically created and destroyed.
-Size must be known at compile time. We can’t use variables to specify the size of a statically
allocated array.
-The compiler handles freeing the memory.

Run Time Memory Allocation (Dynamic Allocation)


Definition: Memory is allocated during the execution (runtime) of the program, upon an
explicit request by the programmer.
How it works: The program requests memory from the OS from a pool of memory called the
head (or free store). The programmer is responsible for returning this memory when done.
Key Characteristics:
-Slower
-Manual Lifetime. Will persists until explicitly deallocated (delete, free).
-Size determined at runtime. Can use variable to specify size.
-Manual management. Failure will result in memory leaks.
Q: What is a memory leak?
It occurs when memory is dynamically allocated but never deallocated. The program loses all
references to the memory, making it impossible to free. This wasted memory accumulates
over time, potentially causing the program to slow down or crash.

Static Keyword
>Variables declared as static in a function are created and initialised once for the lifetime of
the program. (In function)
>Static variables in a class are created and initialised once. They are shared by all the objects
of the class. (In Class)
Friend Function/Classes
They are mechanisms in C++ that break encapsulation in a controlled way. They allow
external functions or other classes to access the private and protected members of a class.
Friend Function
>It is not a member function of the class.
>It is defined outside the class scope, like a normal function.
>It can be called without an object of the class.
>It has access to the class’s private and protected members.
Friend Class
>It is a class whose all member functions are friend functions of another class. If class B is
declared as a friend of class A, then every member function of B can access the private and
protected members of A.
>Not Mutual: Friendship is not bidirectional.
>Not Transitive: Friendship is not inherited.
>Access specifier irrelevant: The friend declaration can be placed anywhere in the class
(private, public or protected section) – it makes no difference.
>Can’t be virtual: Friend functions cannot be declared as virtual.
Q: Why do we need Friend function/class?
1) Operation Overloading: For operators that need to be symmetric (like <<, >>, +, -).
Left hand operand must be an object of the class if not using friend.
2) Improving Performance: When a function needs frequent access to private data, using a
friend can be faster than using public getter/setter function in tight loops.
The friend function eliminates the overhead of multiple function calls.
3) Bridging classes is cleaner.
4) Extending Existing Code: It provides a mechanism for library designers to allow controlled
extension of their classes without compromising encapsulation for all users. They can pre-
emptively declare specific, well-known helper functions as friend, giving them special access
privileges that ordinary user code does not have.

You might also like