OOPs C++
OOPs C++
OOPs C++
Today’s checklist:
OOP concept
Array Vs Structur
Classe
Constructor
Inheritanc
Function overloadin
Function overridin
Object-Oriented Programming (OOP) is like organizing a toolbox. Imagine you have different tools (like a
hammer, screwdriver, and wrench) in a toolbox. Each tool has its own unique purpose and characteristics,
right? That's similar to how OOP works.
Class: Think of a class as a blueprint or a template. It defines the properties (attributes) and behaviors (actions
or methods) that objects made from it will have. For instance, if "Car" is a class, it defines what a car is made of
(like wheels, color, model) and what it can do (drive, honk).
Object: Now, when you use that blueprint to create an actual object, it's like making a real car from the "Car"
blueprint. This object will have specific values for its properties defined in the class. So, you might have a
specific car object named "MyCar" that has four wheels, is red, and is a specific model.
OOP helps in managing big programs by breaking them into smaller, manageable parts (classes). It makes it
easier to reuse code, change things without affecting the whole program, and organize everything neatly.
Java
C++ &+ DSA
DSA
Data Abstraction: OOP allows the creation of complex data types where the implementation details are hidden,
offering only essential information and functionalities. Users interact with objects through interfaces, ignoring
underlying complexities.
Data Encapsulation: This is about bundling data (attributes or properties) and the methods that operate on the
data within a single unit, i.e., an object. Encapsulation provides data protection and control by restricting access
to certain parts of the object.
Inheritance: Inheritance allows a class to inherit properties and behavior from another class. It promotes code
reuse and establishes a hierarchical relationship between classes, enabling new classes to take on
characteristics of existing classes.
Java
C++ &+ DSA
DSA
Polymorphism
Compile time
Run time
Polymorphism Polymorphism
Function
Operator
Virtual
class Player {
int health;
int score;
String name;
class Player {
int health;
int score;
String name;
Player harsh;
Why Classes?
Classes enable us to apply OOP concepts like
Data Abstractio
Data Encapsulatio
Inheritanc
Polymorphis
Modularity and Reusability: Once a class is defined, it can be used to create multiple objects across the
program.
Java
C++ &+ DSA
DSA
Array approach Vs Class
Array Approach:
Limited Functionality: Lacks built-in features like methods and dynamic resizing.
Class Approach:
Encapsulation: Encapsulates data and methods, offering better control and abstraction.
Polymorphism & Inheritance: Supports these concepts for code reuse and relationships between objects.
In essence, arrays are simple, fixed-size collections ideal for homogeneous data, offering uick access. Classes
q
provide flexibility, encapsulation, and dynamic memory, suitable for complex structures with diverse data and
Class Variables: In C++, class variables, also known as member variables or attributes, are declared within the
class definition. They can be initialized in various ways and accessed using object instances or within member
Declaration:
class MyClass {
public:
};
Java
C++ &+ DSA
DSA
Initialization:
Default Initialization:
MyClass obj;
Constructor Initialization:
class MyClass {
public:
int myInt;
double myDouble;
};
constructor
MyClass obj;
Within member functions of the class, you can directly access class variables:
class MyClass {
public:
int myInt;
double myDouble;
cout << "MyInt: " << myInt << endl; // Accessing myInt
};
Java
C++ &+ DSA
DSA
// Using the member function to display values
MyClass obj;
obj.myInt = 30;
obj.myDouble = 7.7;
These approaches demonstrate how to declare, initialize, and access class variables in C++. The choice of
initialization method depends on the context and requirements of your program.
Access specifiers:
1. Public:
2. Private:
3. Protected:
### Usage:
class MyClass {
public:
// ...
private:
// ...
protected:
// ...
};
Understanding these specifiers helps control access to class members, ensuring proper encapsulation and
abstraction in C++ programs.
Java
C++ &+ DSA
DSA
Getters and Setters:
Getters: Functions used to access or retrieve the value of a private member variable.
Example:
class MyClass {
private:
int myVar;
public:
int getMyVar() {
return myVar;
};
Setters: Functions used to modify or set the value of a private member variable.
Example:
class MyClass {
private:
int myVar;
public:
myVar = value;
};
Usage:
Getters allow accessing private variables from outside the class
Setters enable modifying private variables in a controlled manner.
//Code:
MyClass obj;
Getters and setters facilitate controlled access and modification of private member variables, maintaining
encapsulation in C++ classes.
Q. Create a class ‘book’ with name, price, and number of pages as its attributes. The class should contain the
following member functions :
countBooks(int price): This function will return count of all the books that have a price less than the given
price.
isBookPresent(string title) : This will return a boolean value indicating whether any book with the given title
exists or not.
Java
C++ &+ DSA
DSA
Class: Book
#### Attributes:
1. countBooks(int price):
Return Type: Intege
Description: Counts books with prices less than the given value.
2. isBookPresent(string title):
Return Type: Boolea
Description: Checks if a book with the specified title exists.
Implementation Overview:
The `Book` class encapsulates book attributes: name, price, and number of pages
`countBooks(int price)` returns the count of books with prices lower than the given value
`isBookPresent(string title)` checks for the existence of a book by title, returning a boolean value.
Example Usage:
Code:
class Book {
private:
string name;
int price;
int pages;
public:
};
Java
C++ &+ DSA
DSA
// Usage example
Functionality:
countBooks(int price): Helps in finding the count of books priced below a specified value
isBookPresent(string title): Determines whether a book with a specific title exists or not.
These functions enable users to efficiently manage and query book information based on price and title,
respectively, promoting ease of book inventory management.
class MyClass {
// Class definition
};
int main() {
MyClass obj;
return 0;
Example:
class MyClass {
// Class definition
};
int main() {
MyClass obj;
return 0;
Choose between passing by value or reference based on whether modifications to the original object within the
function are necessary or not. Passing by reference is more efficient for large objects and when changes to the
original object are needed within the function.
Code:
class StaticObject {
// Class definition
};
int main() {
// Use obj1...
return 0;
Explanation:
Static Allocation
`StaticObject` is created at compile time
Memory is allocated on the stack
The size of `obj1` is determined at compile time
Automatic memory management within the scope of `main`.
Java
C++ &+ DSA
DSA
Dynamic Allocation in OOP (C++):
Code:
class DynamicObject {
// Class definition
};
int main() {
// Use obj2...
return 0;
Explanation:
Dynamic Allocation
`DynamicObject` is created at runtime using `new`
Memory is allocated on the heap
Size and memory allocation occur during runtime
Manual deallocation (`delete obj2`) is required to release memory and avoid memory leaks.
class OuterClass {
class NestedClass {
};
};
Characteristics:
Access: Nested class has access to private members of the outer class
Scope: Outer class name must be used to access the nested class from outside the outer class
Encapsulation: Provides a way to encapsulate related classes.
Java
C++ &+ DSA
DSA
Example:
class OuterClass {
private:
int outerVar;
public:
class NestedClass {
public:
endl;
};
};
int main() {
OuterClass outerObj;
OuterClass::NestedClass nestedObj;
return 0;
Usage:
Access Control: Nested class can access private members of the outer class
Scoping: Use the `OuterClass::NestedClass` syntax to access the nested class outside the outer class.
Declaration:
Use the class name followed by square brackets and the array size to create an array of objects of that
class.
Example:
class MyClass {
// Class definition
};
int main() {
Java
C++ &+ DSA
DSA
// Access and use array elements as needed
return 0;
Array of classes allows creating multiple objects of the same class in a contiguous block of memory, accessed
via array indexing.
Q. Create a class “cricketer” that contains name of cricketer, his age, number of test matches that he has
played and the average runs that he has scored in each test match. Create an array of data type “cricketer”
to hold records of 20 such cricketers and then write a program to read these records.
#include <iostream>
#include <string>
class Cricketer {
public:
string name;
int age;
int numTests;
double avgRuns;
void inputCricketer() {
void displayCricketer() {
cout << "Test Matches Played: " << numTests << endl;
cout << "Average Runs per Test: " << avgRuns << endl;
};
int main() {
Java
C++ &+ DSA
DSA
// Input cricketer records
cout << "Enter details for Cricketer " << i + 1 << ":" <<
endl;
cricketers[i].inputCricketer();
cout << "Cricketer " << i + 1 << " Details:" << endl;
cricketers[i].displayCricketer();
return 0;
This code defines a `Cricketer` class with attributes for name, age, number of tests played, and average runs
per test. It then creates an array of `Cricketer` objects to store details for 20 cricketers, allowing the user to input
and display those records.
Constructors: Constructors are special member functions in classes that are automatically called when an
object of that class is created. They initialize the object's attributes, allocate resources if necessary, and set up
the object to be used.
Types of Constructors:
Default Constructor:
No parameters
Automatically called when an object is created without arguments
Initializes member variables to default values.
Parameterized Constructor:
Accepts parameters to initialize object attributes
Allows custom initialization of object attributes during object creation.
Copy Constructor:
Creates a new object as a copy of an existing object
Copies the values of attributes from one object to another.
Example:
class Car {
public:
string make;
string model;
int year;
Java
C++ &+ DSA
DSA
// Default Constructor
Car() {
make = "DefaultMake";
model = "DefaultModel";
year = 2020;
// Parameterized Constructor
make = mk;
model = md;
year = yr;
// Copy Constructor
make = car.make;
model = car.model;
year = car.year;
};
int main() {
return 0;
Constructors allow initialization of object attributes when creating objects, enabling custom setups based on
specific requirements.
Destructor:
Definition: Special member function with the same name as the class, preceded by a tilde (`~`)
Purpose: Performs cleanup tasks when the object goes out of scope or is explicitly deleted
Automatic Invocation: Called automatically when the object is destroyed.
Example:
class MyClass {
public:
// Constructor
MyClass() {
// Constructor code
Java
C++ &+ DSA
DSA
// Destructor
~MyClass() {
// Cleanup code
};
int main() {
// Object in scope
object
return 0;
Usage:
Resource Release: Handles cleanup tasks like releasing memory, closing files, etc
Automatic Cleanup: Ensures proper cleanup when the object's lifetime ends
Custom Cleanup Logic: Allows custom cleanup operations specific to the class.
Static Members:
Declared with `static`: Applied to variables and methods within the class
Shared Among Objects: Single copy shared by all instances of the class
Accessed via Class Name: Accessed using the class name, not through objects.
Example:
class MyClass {
public:
};
variable
int main() {
return 0;
Java
C++ &+ DSA
DSA
Usage:
Counters, Constants: Ideal for counters, constants, or global data related to the class.
Static members provide shared attributes and functionalities associated directly with the class, facilitating
Shallow and deep copy are concepts related to copying objects in programming.
Shallow Copy:
Characteristics
If the object contains pointers, it copies the addresses of the pointed data, not the data itself
Both original and copied objects point to the same memory location for pointer members.
Deep Copy:
Characteristics
Copies each member and the data pointed to by pointers to new memory locations
Ensures that the original and copied objects have independent memory locations.
Example:
#include <iostream>
#include <cstring>
class Person {
public:
char* name;
// Constructor
Person(const char* n) {
strcpy(name, n);
// Destructor
~Person() {
delete[] name;
value
Java
C++ &+ DSA
DSA
// Deep Copy
strcpy(name, other.name);
};
Usage:
Shallow Copy: Copies pointer values only, leading to multiple objects sharing the same memory
Deep Copy: Creates separate memory for copied objects, ensuring independent copies with their own
memory.
Understanding the difference between shallow and deep copy is crucial when working with objects that contain
pointers, especially for managing memory and preventing unintended side effects.
Initialisation list
class Student {
public :
int rollNumber;
int age;
};
Initialisation list
In C++, initialization lists are used to initialize class member variables when an object of that class is created.
class Student {
public :
int rollNumber;
int age;
// Constructor body
};
In this example:
The `Student` class has two member variables: `rollNumber` and `age`
The constructor `Student(int r, int a)` initializes these variables using an initialization list `: rollNumber(r),
age(a)`
Inside the constructor, `rollNumber` is initialized with the value of `r`, and `age` is initialized with the value of `a`.
Java
C++ &+ DSA
DSA
Using initialization lists in constructors is a more efficient way to initialize class member variables, especially for
complex objects or when performing initialization for objects that don't have default constructors. It allows for
Function Overloading:
Function overloading in C++ allows creating multiple functions with the same name but different parameters
Characteristics:
Return Type: Overloaded functions can have the same or different return types.
Example:
#include <iostream>
int main() {
calculateArea(int)
calculateArea(int, int)
calculateArea(double)
return 0;
Usage:
Different Parameters: Functions with the same name but different parameters improve code readability
Functionality Extension: Allows a single function name to perform different tasks based on provided
parameters
Java
C++ &+ DSA
DSA
Function overloading enables the creation of functions with the same name but different parameters,
facilitating code organization and enhancing flexibility in function usage within a program.
Inheritance:
Inheritance is a fundamental concept in object-oriented programming (OOP) where a new class, known as the
derived or child class, inherits properties and behaviors from an existing class called the base or parent class.
Code:
#include <iostream>
// Single Inheritance
class Base {
public:
void displayBase() {
};
public:
void show() {
};
// Multiple Inheritance
class Base1 {
public:
void display1() {
};
class Base2 {
public:
void display2() {
};
public:
void show() {
};
// Multi-level Inheritance
public:
void displayDerived1() {
};
public:
void displayMultiLevel() {
};
// Hierarchical Inheritance
public:
void displayDerived2() {
};
// Hybrid Inheritance
public:
void show() {
};
int main() {
DerivedSingle objSingle;
objSingle.displayBase();
objSingle.show();
DerivedMultiple objMultiple;
objMultiple.display1();
objMultiple.display2();
objMultiple.show();
DerivedMultiLevel objMultiLevel;
objMultiLevel.displayBase();
objMultiLevel.displayDerived1();
Java
C++ &+ DSA
DSA
objMultiLevel.displayMultiLevel();
Derived2 objDerived2;
objDerived2.displayBase();
objDerived2.displayDerived2();
DerivedHybrid objHybrid;
objHybrid.display1();
objHybrid.display2();
objHybrid.show();
return 0;
Diamond Problem
The Diamond Problem is a classic issue in multiple inheritance where ambiguity arises due to the presence of
two instances of a common base class within a complex inheritance hierarchy.
B derives A, C derives A
Now D has 2 instances of A, causing ambiguity while accessing A's properties or methods.
This situation results in ambiguity when the class D tries to access the members inherited from class A, as it has
two paths to reach class A's members, through B and C. Resolving this ambiguity often requires explicit scoping
or virtual inheritance to ensure a single instance of the shared base class A. Virtual inheritance helps avoid
duplicate instances of the base class within the hierarchy, ensuring that there's only one instance of A in the
derived class D.
#include <iostream>
// Base class A
class A {
public:
void display() {
};
Java
C++ &+ DSA
DSA
int main() {
D obj;
return 0;
Function Overriding:
When a function of base class is redefined in it’s derived class thereby replacing the base class's
implementation with its own, it’s called function overriding.
Accessing through Scope Resolution Operator:
#include <iostream>
// Base class
class Base {
public:
void display() {
};
public:
void display() {
};
int main() {
Derived obj;
obj.Base::display();
return 0;
Java
C++ &+ DSA
DSA
In this code:
`obj.display()` calls the overridden `display()` function in the `Derived` class
`obj.Base::display()` explicitly calls the `display()` function from the `Base` class using the Scope Resolution
Operator.
#include <iostream>
// Base class
class Base {
public:
void display() {
};
public:
void display() {
};
int main() {
Derived obj;
return 0;
In this code:
`ptr->display()` through a pointer of type `Base` to an object of type `Derived` invokes the overridden
`display()` function in the `Derived` class.
Function overriding allows the derived class to provide a specific implementation for a function defined in the
base class, enabling polymorphic behavior in C++.
Virtual Functions:
Virtual functions make sure the correct function is called for an object, regardless of the pointer used for calling
it.
virtual functions in C++ enable polymorphic behavior by allowing the correct function to be called for an object,
regardless of the pointer used for the call. Here's an example illustrating virtual functions:
Java
C++ &+ DSA
DSA
#include <iostream>
class Base {
public:
// Virtual function
};
public:
};
int main() {
delete ptrBase;
delete ptrDerived;
return 0;
In this code:
`display()` is a virtual function in the `Base` class
The `Derived` class overrides the `display()` function
Both `ptrBase` and `ptrDerived`, although of type `Base`, call the correct overridden `display()` function based
on the actual object they point to. This behavior is achieved due to the function being declared as virtual.
Virtual functions ensure that the correct function is called based on the actual object being pointed to, enabling
polymorphic behavior and supporting dynamic binding, which happens at runtime.
Abstract Class:
An abstract class in C++ is a blueprint that cannot be instantiated directly, often containing one or more pure
virtual functions. It's designed to be inherited by other classes, which must provide implementations for its pure
virtual functions.
Java
C++ &+ DSA
DSA
Key Points:
Cannot be instantiated: Abstract classes cannot create objects directly
May contain pure virtual functions: Functions declared as pure virtual (`virtual void func() = 0;`) make the
class abstract
Provides an interface: Serves as a template for derived classes to inherit and implement.
Example:
#include <iostream>
// Abstract class
class Shape {
public:
};
public:
};
int main() {
return 0;
Operator overloading:
Operator overloading in C++ enables custom classes to define how standard operators behave when applied
to objects of those classes.
Key Points:
Syntax: `returnType operator symbol(parameters) { /* implementation */ }
Operators Overloaded: Arithmetic, Assignment, Comparison, Increment/Decrement, Logical, Bitwise, etc
Member vs. Non-member Overloading: Operators can be overloaded as member functions or global
functions
Example: Overloading `+` operator for a `Point` class to perform addition.
Java
C++ &+ DSA
DSA
Example:
Code:
#include <iostream>
class Point {
private:
int x, y;
public:
Point temp;
temp.x = x + other.x;
temp.y = y + other.y;
return temp;
};
int main() {
return 0;
`operator+` is overloaded for the `Point` class, allowing `+` to add two `Point` objects
`p1 + p2` uses the overloaded `+` operator for `Point` objects, performing the specified addition operation.
Const Keyword:
In Object-Oriented Programming (OOP), `const` is used to ensure object integrity, define immutability, and
enforce certain behaviors within classes.
Usage in OOP:
1. Const Member Functions:
Guarantee that member functions don't modify object state
Promote const-correctness and prevent unintended changes.
Java
C++ &+ DSA
DSA
class Circle {
public:
return radius;
};
2. Const Objects:
Define objects that can't be modified after initialization
Ensure object's state remains unchanged.
const Circle smallCircle(5.0); // Const object
3. Const References and Pointers:
Pass arameters to functions ithout allo ing modifications
p w w
4. Mutable Keyword:
A llo s modification of s ecific data members ithin a const member function
w p w ` `
U seful for cases here some members need modification des ite the function being const .
w p ` `
class Rectangle {
private:
};
Example:
class Circle {
public:
};
`const usage in
` ensures object immutabilit maintains const correctness and defines beha iors that
OOP y, - , v
Java
C++ &+ DSA
DSA
Q. Predict the output
class Student {
public :
int age;
};
int main() {
Ans: 100 23
It will print the values of roll number (which is initialized with 100) and age (initialized with 23) for the Student
object s1.
Friend Function:
Not a Member Function: Defined outside the class, but declared inside using the `friend` keyword
Access to Private Members: Granted access to private and protected members of the class it's declared as a
friend
Usage: Useful for providing specific functions access to private class details without being a member.
Example:
#include <iostream>
class MyClass {
private:
int secretData;
public:
};
int main() {
MyClass obj;
return 0;
Java
C++ &+ DSA
DSA
`displaySecret()` is a friend function of `MyClass`, accessing the private member `secretData`
The `friend` keyword allows the function access to the private members of `MyClass`.
class Student {
public :
int rollNumber;
int age;
};
int main() {
Student s1;
Student s2 = s1;
s1.rollNumber = 101;
s1.age = 20;
Ans: 0 0
Explanation: Since s2 is created using the default copy constructor before any modifications are made to s1, it
will contain the default values (zero-initialized) for rollNumber and age. Therefore, s2.rollNumber and s2.age will
both be 0.
class Student {
public :
int rollNumber;
return rollNumber;
};
int main() {
Student s;
s.rollNumber = 101;
Explanation: The code won't compile due to the attempt to access a non-static member (`rollNumber`) from a
static member function (`getRollNumber()`), which isn't allowed in C++. Static member functions can't directly
access non-static members.
Java
C++ &+ DSA
DSA
Q. Create a class ‘person’ having attributes as age and weight. Access its object using pointers.
Code:
class Person {
public:
int age;
double weight;
};
int main() {
Person person;
person.age = 25;
person.weight = 65.5;
return 0;
In main(), an object of Person class named person is created and its attributes (age and weight) are assigned
values.
A pointer ptrPerson of type Person is initialized to the address of the person object.
The arrow operator (->) is used to access the members of the object person through the pointer ptrPerson,
displaying its age and weight
Q. maruti.engine.bolts = 25 ;
Which of the following is True?
Solution: The statement maruti.engine.bolts = 25; indicates that engine is a member of maruti, and within
engine, there exists a member named bolts.
So this tell bolts is just an int not a class, and maruti and engine are class, and engine class in nested in maruti
class.
Java
C++ &+ DSA
DSA
#include <iostream>
class Shape{
public :
int height;
int width;
};
int main() {
s -> height = 1;
Ans: 1
s -> height = 1; sets the height attribute of the dynamically allocated Shape object to 1.
Protecte
Stati
Publi
Private
Ans: Private
Explanation: Members without an explicit access specifier (public, protected, or private) are private.
Strin
Boolea
Clas
All data types can be included
Ans: Class, In object-oriented programming, objects are instances of classes.
Which functions are declared inside a class have to be defined separately outside the class?
Static function
Const function
Inline function
Member functions
Java
C++ &+ DSA
DSA
Answer: D) Member functions
Member functions declared inside a class have to be defined separately outside the class. They are much like
normal functions.
#include <iostream>
class Student{
public :
char *name;
int rollNo;
Student(int num){
rollNo = num;
void print(){
cout<<rollNo;
};
int main() {
Student s(12);
s.print();
Ans: 12
Explanation: s(12) initializes the rollNo member of the s object with the value 12,s.print(); invokes the print()
function, which outputs the value of rollNo, resulting in the output of 12.
Java
C++ &+ DSA
DSA
Q. Choose the appropriate option
Declaratio
Implementatio
Prototyp
Functioning
Ans: Implementation
Explanation: Functions go in the Implementation section of a class to provide the actual code defining their
behavior and operations on the class's data members.
Q. When a program is executed, the ____ interacted by sending a message to one another.
Object
Classe
Operating syste
Memory
Ans: 1) Objects
Explanation: When a program is executed, the objects interact by sending a message to one another. For
example, if "customer" and "account" are two objects in a program, then the customer object may send a
message to the account object requesting the back balance.
Java
C++ &+ DSA
DSA
THANK
YOU !