0% found this document useful (0 votes)
15 views212 pages

Object Oriented Programming

Uploaded by

Tarushi vaish
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
15 views212 pages

Object Oriented Programming

Uploaded by

Tarushi vaish
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 212

UNIT 1 OOP

Dr. Bhawna Narwal


• Programmers write instructions in various programming
languages to perform their computation tasks such as:
(i) Machine level Language
(ii) Assembly level Language
(iii) High level Language

• Machine level Language : Machine code or machine


language is a set of instructions executed directly by a
computer's central processing unit (CPU). Each instruction
performs a very specific task, such as a load, a jump, or an
ALU operation on a unit of data in a CPU register or
memory. Every program directly executed by a CPU is
made up of a series of such instructions.
• Assembly level Language : An assembly language (or
assembler language) is a low-level programming language for
a computer, or other programmable device, in which there is
a very strong (generally one-to-one) correspondence
between the language and the architecture's machine code
instructions. Assembly language is converted into executable
machine code by a utility program referred to as an
assembler; the conversion process is referred to as assembly,
or assembling the code.
• High level Language : High-level language is any
programming language that enables development of a
program in much simpler programming context and is
generally independent of the computer's hardware
architecture. High-level language has a higher level of
abstraction from the computer, and focuses more on the
programming logic rather than the underlying hardware
components such as memory addressing and register
utilization.
• The first high-level programming languages were designed in the
1950s. Now there are dozens of different languages, including Ada ,
Algol, BASIC, COBOL, C, C++, JAVA, FORTRAN, LISP, Pascal, and
Prolog.
• Such languages are considered high-level because they are closer to
human languages and farther from machine languages.
• In contrast, assembly languages are considered low level because
they are very close to machine languages.
• The high-level programming languages are broadly categorized in
to two categories:
 Procedure oriented programming (POP) language.
 Object oriented programming (OOP) language.
Procedure oriented programming
(POP) language
 In the procedure oriented approach, large programs are divided into smaller
programs known as functions.
 In POP, a program is written as a sequence of procedures or function.
 In POP, each procedure (function) contains a series of instructions for performing a
specific task.
 During the program execution each procedure (function) can be called by the other
procedures.
 To call a procedure (function), we have to write function name only.
 While we concentrate onto the development of functions, we give very little
attention to the data that are being used by various functions.
 In POP, the major emphasis is on procedure (function) and not on the data.
 In a multi-function program, many important data items are placed as global so
that they may be accessed by all the functions. Each function may have its own
local data.
 Global data are more vulnerable to an accidental change by a function. In a large
program it is very difficult to identify what data is used by which function.
 Examples of procedural oriented programming language are COBOL, FORTRAN,
PASCAL, C programming language etc.
Characteristics of procedure-oriented
programming:-
 While designing a program, POP
follows a top-down programming
approach.
 Majority of the functions allows
global data to be shared.
 It also divides larger programs into
smaller parts called as functions.
 It allows a free data movement
around the system from functions
to functions.
 Data is transformed by the
functions from one form to another.
 It gives importance to the concept
of the functions.
Advantages of Procedure Oriented
Programming (POP)
1. The program is divided into functions that
have some specific tasks.
2. Almost all functions share global declared
data.
3. The data can easily move from functions to
functions.
• Drawbacks:-
• In POP, global data can be accessed & changed by
any procedure (function) so there is no data
security.
• In case if we want to change type of data of
global data, then we also need to resolve all
functions that access the data. Due to this it may
happened that some errors will occurs
• POP does not model real world problems because
functions are action oriented. In the physical
world we deal with objects such as people and
cars.
• Such objects aren’t like data and they aren’t like
functions. Complex real-world objects have both
attributes and behavior
NEED FOR OBJECT ORIENTED
PROGRAMMING
• Object-oriented programming was developed because limitations were
discovered in earlier approaches to programming.
• OOP treats data as a critical element in the program development and
does not allow it to flow freely around the system.
• In OOP, the major emphasis is on data rather than procedure
(function).
• It ties data more closely to the function that operate on it, and
protects it from accidental modification from outside function.
• OOP allows decomposition of a problem into a number of entities
called objects and then builds data and function around these objects.
• The data of an object can be accessed only by the function associated
with that object. However, function of one object can access the
function of other objects.
• C++, Java, Dot Net, Python etc are the example of Object oriented
programming (OOP) language.
Example
• The simplest way to explain object-orientated programming
to a kid is to use something like a car as an example. A car
has a model name, a colour, a year in which it was
manufactured, an engine size and so on.
• We would therefore create a Car object with the name,
colour, engine size and year as attributes.
• For every new car we use, we would use the car object. For
instance, we can have a 2019 Blue BMW or a 2017 Red
Audi. In each instance we would reuse the code contained
in the original object.
• The main principles of object-oriented programming are
encapsulation, abstraction, inheritance and polymorphism.
Features of OOP (Object Oriented
Programming):-
• Class
• Object
• Encapsulation
• Data Abstraction
• Inheritance
• Polymorphism
• Data binding
• Message Passing
Application of Object Oriented
Programming:-
• User interface design such as windows, menu
• Real Time Systems such as Control system for
cars, aircraft, space vehicles etc
• Office automation system such as Document
Management System i.e. Word processing
system, spread sheet software etc
• AI and Expert System
• Neural Networks and parallel programming
System
• Decision support system etc
Advantages of OOP:-
1. Improved software-development productivity:
• Object-oriented programming is modular, as it provides separation
of duties in object-based program development.
• It is also extensible, as objects can be extended to include new
attributes and behaviors.
• Objects can also be reused within an across applications. Because of
these three factors – modularity, extensibility, and reusability –
object-oriented programming provides improved software-
development productivity over traditional procedure-based
programming techniques.
2. Improved software maintainability:
• Since the design is modular, part of the system can be updated in
case of issues without a need to make large-scale changes.
• 3. Faster development:
• Reuse enables faster development. Object-oriented
programming languages come with rich libraries of objects,
and code developed during projects is also reusable in
future projects.
• 4. Lower cost of development:
• The reuse of software also lowers the cost of development.
Typically, more effort is put into the object-oriented
analysis and design, which lowers the overall cost of
development.
• 5. Higher-quality software:
• Faster development of software and lower cost of
development allows more time and resources to be used in
the verification of the software. Although quality is
dependent upon the experience of the teams, object
oriented programming tends to result in higher-quality
software.
• Advantages of Object Oriented Programming:
• OOP concept allows breaking the project or software into smaller
modules or chunks so it makes debugging or testing easy for
programmers.
• OOP promotes the reusability of code. For example, using
inheritance you can use the code of the parent class in the child
class and can eliminate the duplicate code.
• OOP systems or software can be scaled easily.
• As OOP provides the concept of data hiding, it allows programmers
to develop secure programs or projects in which any unauthorized
user can’t invade or attack.
• OOP concept provides the flexibility in writing code using
polymorphism, as you can use the same name function to provide
its implementation according to your usage or requirements.
• OOP systems are easily maintainable.
Disadvantages of OOP:-
1. Larger program Size:
• Object oriented programs are much larger than other programs. In the early days
of computing, space on hard drives, floppy drives and in memory was at a
premium. Today we do not have these restrictions.
2. Effort:
• Object oriented programs require a lot of work to create. Specifically, a great deal
of planning goes into an object oriented program well before a single piece of code
is ever written. Initially, this early effort was felt by many to be a waste of time. In
addition, because the programs were larger, coders spent more time actually
writing the program.
3. Speed:
• Object oriented programs are slower than other programs, partially because of
their size. Other aspects of Object Oriented Programs also demand more system
resources, thus slowing the program down.
In Short,
• It requires more resources.
• Dynamic behaviour of objects requires RAM storage.
• Detection and debugging is harder in complex applications when the message
passing is performed.
• Inheritance makes their classes tightly coupled, which affects the reusability of
objects.
Key Differences Between OOP and POP
 POP is procedure-oriented programming while OOP is object-oriented
programming.
 The main focus of POP is on “how to get the task done” it follows the flow
chart to get the task done. OOP’s main focus is on data security as only
the objects of a class are allowed to access the attributes or function of a
class.
 The functions are small units of the large programs or a sub-program that
execute to get the main task done. In contrast, OOP attributes and
functions of the class are divided among the objects.
 In POP, there is no specific accessing mode to access attributes or
functions in the program. Conversely, in OOP there are three accessing
modes “public”, “private”, “protected”, that are used as an accessing
method to access attributes or functions.
 POP does not support the concept of
Overloading/polymorphism. On the contrary, OOP
supports Overloading/Polymorphism, which means
using the same function name for performing different
functions. We can overload functions, constructor, and
operators in OOP.
 There is no concept of inheritance in POP whereas,
OOP supports inheritance which allows using the
attribute and functions of other class by inheriting it.
 POP is less secure as compared to OOP because in OOP
the access specifier limits the access to attributes or
functions which increase the security.
 In POP if some data is to be shared among all the
functions in the program, it is declared globally outside
all functions. While in OOP the data member of the
class can be accessed through the member functions of
the class.
In POP there is no concept of the friend
function.
As against, in OOP there is a concept of friend
function which is not the member of the class,
but because it is friend member it can access
the data member and member functions of
the class.
There is no concept of virtual classes in POP
whereas in OOP, the virtual functions support
polymorphism.
COMPARION OF PROGRAMMING
PARADIGMS
CHARACTERISTICS OF OOP LANGUAGE
1. Emphasis is on data rather than procedure (function).
2. Programs are divided into objects.
3. Functions that operate on the data of an object are
tied together in the data structure.
4. Data is hidden and cannot be accessed by external
function.
5. Objects may communicate with each other through
function.
6. New data and functions can be easily added
whenever necessary.
7. Follows bottom up approach in program design.
OOP importance:
• In real life, you deal with a lot of objects or entities like a car, bike,
animal, etc. So, programmers need software to be similar to real-
world entities.
• Real-world objects have properties such as car model, car size for
car, name, age, occupation for human, etc. and real-world entities
or objects can do various things like bikes can move, people can
walk or eat, etc.
• So OOP concept helps the program to be closer to real-world
objects.
• Also, OOP allows code to be reusable and make it more simple.
• For example, you don’t have to define each room in the hotel
management system every time, you can use OOP, to create a class
for the room and use it whenever required.
INTRO TO OOP CONCEPTS
OBJECTS
• Objects are the basic run-time entities (= things that exist only
during program execution somewhere in memory. They have
no life outside program execution. For example, in C , the run-
time entities are structures, basic types, etc .) in an object-
oriented system. They may represent a person, a place, a bank
account, a table of data or any item that the program must
handle.
• The fundamental idea behind object oriented approach is to
combine both data and function into a single unit and these
units are called objects.
• The term objects means a combination of data and program
that represent some real word entity.
CLASSES
• A group of objects that share common
properties for data part and some program
part are collectively called as class.
• In C ++ a class is a new data type that contains
member variables and member functions that
operate on the variables.
• A class is thus a description of a number of
similar objects. This fits our non-technical
understanding of the word class.
CLASS vs Object
• Let's see some real life example of class and
object in java to understand the difference
well:
• Class: Human Object: Man, Woman
• Class: Fruit Object: Apple, Banana, Mango,
Guava wtc.
• Class: Mobile phone Object: iPhone,
Samsung, Moto
• Class: Food Object: Pizza, Burger, Samosa
Example
• For example, consider the Class of Accounts.
• There may be many accounts with different names and
types, but all of them will share some common
properties, as all of them will have some common
attributes like balance, account holder name, etc. So
here, the Account is the class.
• Object is an instance of a class.
• All data members and member functions of the class
can be accessed with the help of objects.
• When a class is defined, no memory is allocated, but
memory is allocated when it is instantiated (i.e. an
object is created).
• For Example, considering the objects for the
class Account are SBI Account, ICICI account, etc.
DETAILED EXAMPLE
• Suppose you are working on a “Hotel Management System” project for a hotel.
• If you think of developing a system using procedural programming (which is based on
procedures or routines that contains a series of steps to be carried out for working) then the
system can be viewed in terms of work happening in a hotel that is check-in at the hotel,
check-out from hotel, manage rooms, manage bookings of room etc.
• However, OOP concept revolves around real-world objects and their usages. Thus in OOP,
Hotel Management System can be thought of in terms of the objects involved. Now the
question arises, What are objects? So objects are the real-world entity around which our
system revolves or in other words system is dependent on objects. In the hotel management
system what all objects you can think of in a hotel?
• – “Room” which can represents the rooms in that hotel
• – “Customer” which represents the customer who will visit to the hotel to book room
• – “Booking” which can represents the booking of the room which will be done by customer
• So, all these objects represent real world entities and make our system similar to real world
entities. Thus you can say that the Object-Oriented programming concept views problems in
terms of real-world objects.
• Now, to describe or represent real-world objects or entities you need Classes. Class is used to
bind characteristics(variables) and functionality. When an object is created which belongs to
that class, that object has all the characteristics and methods which were defined in the class
and has their specific value according to that object.
• For example, in the hotel management system, to represent a room object
in terms of class you have to define the properties of the room like
room_number, room rent etc as well as methods (functions related to it)
which are specific to that room only, for example every room in the hotel
has CheckIn and CheckOut functionality of its own.
• So every room will have some common characteristic properties(which
could be number, rent, size, Ac/Non Ac, status) but the values associated
(such as 102 room number, 2000 Rs per night, XL size, AC room, Occupied)
to these properties will change for every room independently. Such
characteristics are referred to as properties of the object, and their values
as state.
• Similar to the properties, every room will also have some functionalities
which will help the system to access, fetch and update the values of the
properties of the room. Such as, if a room has Status value equal to ‘Vacant’
and a new guest arrives and occupies that empty room. The system must
update the status of the room from ‘Vacant’ to ‘Occupied’. So, to perform
this update, the room must have a functionality, say, ‘toggleStatus’. The
functionality of this function will be switching the status of the room
between ‘Vacant’ and ‘Occupied’. All these types of functionalities (which
update and fetch the characteristics values) are known as methods of the
object.
• So now concluding a ‘Room’ class will be a blueprint
containing the properties and the methods, but the class
will not have any state but whenever it’s object is created,
the object’s properties will have some values and contain
all the functions described in blueprint(class). .
• You can say that class represents a group of the same or
similar type of objects. So, the “Room” class in the hotel
management system is used to represent all the rooms of a
hotel.
• Thus you can say that the OOP(Object Oriented
Programming) /concept is a programming paradigm or
concept that aims to implement real-world objects. If you
can identify the objects in your code which are similar to
real life objects and can structure your code accordingly in
classes and objects then you can say that OOP principles
are used in your code.
• So classes and Objects are the basic building blocks of the
OOP concept. C++, Java, Javascript are major Object
Oriented languages.
These are basic concepts or characteristics of OOPS. We will take a deeper look at each
one:
Class A class can be considered as a blueprint or template for creating similar types of
objects. Classes are a user-defined data type that defines two things:
 Attributes or data
 Behavior or methods
Individual objects are then created using the class or blueprint.
For example, in the hotel management system mentioned above, you can create a
class “Room” to define each room in the hotel which will have attributes and
behavior of each room. So room class can contain the following fields or attributes:
– room_number
– room_rent
– room_status
And “Room” class can contain following methods to use above given fields:
– checkIn() : This function will be used to checkin in the room.
– checkout() : This function will be used to checkout of the room.
– getRoomStatus() : This function will give the status of the room whether it is
occupied or not.
So “Room” class here is a template to represent a room in the hotel and you have to
create or instantiate the Room class to represent an individual real-world thing that
is a room of the hotel.
• In C++, class is defined using the “class”
keyword and then its name is there followed
by the body of class in curly braces ending
with a semicolon.
• So to represent class for a room, here is the
syntax:
class Room {
// data
//methods
};
The body of the class will contain methods and
data related to Room.
Object
• As described at the starting of the article, Objects are real-world entities that
contain specific data or information, so you can say that objects are instances of
classes that contain specific data or information related to that object. For
example, we have defined the “Room” class to represent a hotel room. So to
create an instance or object of the “Room” class you have to define an object for
the “Room” class which represents a specific room of the hotel. In C++ to define
object syntax is as follows:
class_name object_name;
• Suppose you have to define room r1, so r1 will contain all the information specific
to that room in the hotel. So to define room r1 for the hotel you can instantiate
the “Room” class or create the object of Room class like this:
Room r1;
• So, here r1 is an instance or object of class Room and will have its specific
room_number, room_rent, room_status.
• Note: Whenever you define a class, only the properties of the object are defined,
no memory is allocated. So to allocate memory and to use data and functions of a
class you have to create objects of that class.
Methods and Attributes
• Methods: Methods are functions that are defined in class body or
definition and they can perform various actions like updating the
field or data of the object of the class, showing the data of the
object of the class, etc.
• Methods generally specify the behavior of a class. When the objects
of a class are created, these objects can call the methods of the
class. In the above example of Room class,
• – checkIn()
• – checkOut()
• – getRoomStatus()
• These are the methods that are defined in the class and these can
be called using the objects of class “Room”.
• Methods usually promote the reusability of code. Suppose, there is
a piece of code that is used in code many times, so instead of
writing the same code again and again you can put that code into
methods and you can use that method.
• It also helps programmers to debug the code easily. The
programmer has to check errors only at one place that is in the
method instead of checking the whole code.
• Attributes : Attributes are the data fields or
information that are specific to an object. When an
object of a class is created all the information specific
to that object is stored in attributes or fields. In the
above example of Room class,
• – room_number
• – room_rent
• – room_status
• These are attributes defined in the “Room” class.
Suppose you create object r1 of Room class, then you
can store information related to that particular room r1
in the attributes mentioned above.
• Note: You can use the “.” operator to access the
attributes of objects or you can use getters and setters
for objects.
How to Structure OOP Programs:
• Let’s take a real-life example of the Hotel Management system which we
took in starting by extending it further and design an OOP program.
Suppose you have to create software for a hotel that can handle all the
rooms, their status, bookings, services, payments, then how will you
create simple, reusable software to manage the hotel.
• As there will be a lot of categories of rooms in the hotel and you have to
maintain the status of each room and its booking and payments, so you
can use classes and objects for creating the software.
• You have to identify real-life objects in the given scenario and club all the
object-related information in class and you can use that class by creating
objects of that class.
• In the given example here is how a programmer can think of creating
classes:
• – Room class: To manage rooms of the hotel
• – Booking class: To manage all booking of the hotel
• – Payment class: To manage all operations of payments of bookings
• – Customer class: To manage all operations related to the customer who
will come to the hotel to book a room.
• Now classes are defined programmer can think of defining attributes of
each class:
 – Room class : room_no, room_category, room_status, room_rent
 – Booking class: booking_id, booking_date, booking description
 – Payment class : payment_id, payment_amount,
payment_customer_id
 – Customer class: customer_id_number, customer_name,
customer_room_number
• These all are the possible attributes which you can take in each class.
• Now a programmer can think of adding methods or logic in each class
according to his or her use cases or requirements. Suppose in Room
class the programmer can add methods like this: checkIn(), checkOut(),
getRoomStatus() and so on…
• So here is a diagram representing the design of the OOP program in
which you can group together related data(fields or variables) and
behaviors(methods) to form a simple template or class:
ENCAPSULATION
• Encapsulation is an object oriented concept in
which data and functions are combined in a
single unit called class.
• Encapsulation is a process of combining member
functions and data members in a single unit
called a class.
• The purpose is to prevent access to the data
directly. Access to them is provided through the
functions of the class.
• It is one of the popular features of Object-
Oriented Programming(OOPs), which helps
in data hiding.
Data Encapsulation
• Wrapping similar data members and functions
inside a class together helps in data hiding and
with this, you can hide sensitive information and
limit the access to the internal state only.
• NOTE: Don't get confused between encapsulation
and data hiding.
• Encapsulation refers to the bundling of related
fields and methods together and it can be used to
achieve data hiding. Encapsulation is not itself
data hiding.
• The general form of encapsulation looks like this:
class class_name {

private:
datatype member_variables;
datatype member_functions;

public:
datatype member_variables;
datatype member_functions;
};

int main() {
class_name object_name;
}
The code above shows that a class acts like a single unit consisting of
member variables and member functions.
Let's take one example to understand the concept of data encapsulation:
class A{

private:
int var;

public:
void takeInput()
{
cin >> var; In the above example, as we can see
} class A acts like a single unit consisting of
void display()
{
member variables and member functions
cout << var << endl; operating on those member variables. Here,
} the variable “var” is private.
Hence, this variable can be accessed only by
};
the members of the same class and is not
int main(){ accessible anywhere else. Hence the outside
classes will be unable to access this variable
A obj; which will help in achieving data hiding.
obj.takeInput();
obj.display();
}
OUTPUT:
20
20
Real-life example
• Suppose you go to an automatic teller machine(ATM) and
request money. The machine processes your request and
gives you money.
• Here ATM is a class. It takes data from the user(money
amount and PIN) and displays data in the form of icons and
options. It processes the request(functions). So it contains
both data and functions wrapped/integrated under a single
ATM. This is called Encapsulation.
• Suppose you have a profile on some social networking
website, say Facebook. If your profile password is declared
as a public variable, anyone can see your password and log
in to your Facebook account. So, would you like it?
Obviously No.
So, Facebook declares your password as private to make
your account safe so that anyone can not log in to your
account. So the other details of your account or post you
share can be made public or private by you. So you can see
the data hiding concept here.
Advantages/disadvantages of Encapsulation in C++
Advantages
• The main advantage of using Encapsulation is to hide the
data from other methods. By making the data private,
these data are only used within the class, but these data
are not accessible outside the class.
• Protects data from unauthorized users
• This concept is applicable in the marketing and finance
sector, where there is a high demand for security and
restricted data access to various departments.
• Encapsulation helps us in binding the member functions
and data of a class.
• Encapsulation also helps us make code flexible, which is
easy to change and maintain.
Disadvantage
• Private data cannot be accessed outside the class.
How to Use Encapsulation in C++?
• First, make all the data
members private.
• Then getter(gets the value of data
member) and setter (sets the value of
data member)functions should be
performed for each data member.
• In this, we are adding an
employee’s salary (full-time and
overtime). We have a data member
salary declared as private, as you can
see. That means it can be used within
that class only and not even in
the main(). If we want to use this
function in the main function, we
should use the getter and setter
functions. So here we have a getter
function getSalary() and setter
function setsalary().
• Inside main(), we create an object of
the company class. Now we can use
the setSalary() method to set the value
of the full-time and overtime salaries.
Then we call the getSalary() method on
the object to return the value.
ENCAPSULATION
Abstraction:
• Process of picking the essence of an object you really need
• In other words, pick the properties you need from the object
• Example:
a. TV - Sound, Visuals, Power Input, Channels Input.
b. Mobile - Button/Touch screen, power button, volume button, sim port.
c. Car - Steering, Break, Clutch, Accelerator, Key Hole.
d. Human - Voice, Body, Eye Sight, Hearing, Emotions.
Encapsulation:
• Process of hiding the details of an object you don't need
• In other words, hide the properties and operations you don't need from the object but are
required for the object to work properly. Example:
a. TV - Internal and connections of Speaker, Display, Power distribution b/w components,
Channel mechanism.
b. Mobile - How the input is parsed and processed, How pressing a button on/off or changes
volumes, how sim will connect to service providers.
c. Car - How turning steering turns the car, How break slow or stops the car, How clutch
works, How accelerator increases speed, How key hole switch on/of the car.
d. Human - How voice is produced, What's inside the body, How eye sight works, How
hearing works, How emotions generate and effect us.
ABSTRACTION
1. What is Abstraction?
• Abstraction is the process of hiding the internal details of an
application from the outer world. Abstraction is used to describe
things in simple terms. It’s used to create a boundary between the
application and the client programs.
2. Abstraction in Real Life
• Abstraction is present in almost all the real life machines.
• Your car is a great example of abstraction. You can start a car by
turning the key or pressing the start button. You don’t need to
know how the engine is getting started, what all components your
car has. The car internal implementation and complex logic is
completely hidden from the user.
• We can heat our food in Microwave. We press some buttons to set
the timer and type of food. Finally, we get a hot and delicious meal.
The microwave internal details are hidden from us. We have been
given access to the functionality in a very simple manner.
• Objects are the building blocks of Object-
Oriented Programming.
• An object contains some properties and
methods. We can hide them from the outer
world through access modifiers.
• We can provide access only for required
functions and properties to the other
programs.
• This is the general procedure to implement
abstraction in OOPS.
Data Abstraction
• Data Abstraction is a mechanism or technique of showing the users only
the necessary interface details and hiding the complex and complicated
implementation details from the user. It's the process of providing only the
essential details to the outside world and hiding the internal complex
details.
• We can understand the concept of data abstraction with the help of an
example: let's suppose you want to sort a list of numbers in your C++
program, so for that, you can make a call to the sort() function without
knowing what algorithm the function actually uses to sort the given
values. Similarly, we use the pow() function to calculate the power of a
number without knowing the algorithm the function follows.
• This is done to hide the internal unnecessary details from the end-
users and to make their task easier.
Data abstraction can be achieved by two types:
 Using classes.
 Using header files.
Abstraction Using Classes: An abstraction can be achieved
with the help of classes. As we know that a class is a
group of all the data members and member functions
and it binds them all into a single unit.
A class has the responsibility to determine which data
member is to be visible and accessible outside the class
and which is not with the help of the access specifiers.
Let's see a simple example to understand abstraction using
classes:
class Base
{
private: In this example, abstraction is achieved using
int num1, num2, subtract; // private variables classes. Class Base contains the private
members num1, num2, and subtract, and are
public: only accessible by the member functions of
void fun()
the class.
{
cout << "Enter two numbers:" << endl;

cin >> num1 >> num2;

cout << "The difference between the two numbers is:" << endl;
if(num1 > num2)
{
subtract = (num1 - num2);
}
else
{
subtract = (num2 - num1);
}
cout << subtract << endl; OUTPUT:
} Enter two numbers:
};
int main() 10
{ 60
Base obj; The difference between the two numbers is:
obj.fun();
}
50
• Abstraction in Header Files: Abstraction can also be achieved using
header files. As we have seen above, the pow() function is used
to calculate the power of a number without actually knowing which
algorithm function uses to calculate the power. We can simply use the
pow() function in our code after importing the necessary header files.
Thus, we can say that header files hides all the implementation details
from the user.
• Let's take one simple example to understand abstraction in header files:
#include<math.h>

int main()
{
cout << pow(4, 3) << endl;
}

OUTPUT
64
• As we can see from the above code, we can simply use the pow() function
in our code after importing the necessary header file i.e math.h, even
without knowing which algorithm the pow() function uses to calculate the
power.
• Consider a real-life example of a man driving a car.
The man only knows that pressing the accelerator will
increase the speed of the car or applying brakes will
stop the car but he does not know how on pressing the
accelerator the speed is actually increasing, he does not
know about the inner mechanism of the car or the
implementation of the accelerator, brakes, etc in the
car. This is what abstraction is.
• Types of Abstraction:
• Data abstraction – This type only shows the required
information about the data and hides the unnecessary
data.
• Control Abstraction – This type only shows the
required information about the implementation and
hides unnecessary information.
Abstraction using Classes
• We can implement Abstraction in C++ using classes. The class helps us to group
data members and member functions using available access specifiers. A Class can
decide which data member will be visible to the outside world and which is not.

Abstraction in Header files


• One more type of abstraction in C++ can be header files. For example, consider the
pow() method present in math.h header file. Whenever we need to calculate the
power of a number, we simply call the function pow() present in the math.h header
file and pass the numbers as arguments without knowing the underlying algorithm
according to which the function is actually calculating the power of numbers.
Abstraction using Access Specifiers
• Access specifiers are the main pillar of implementing abstraction in C++. We can
use access specifiers to enforce restrictions on class members. For example:
• Members declared as public in a class can be accessed from anywhere in the
program.
• Members declared as private in a class, can be accessed only from within the class.
They are not allowed to be accessed from any part of the code outside the class.
• We can easily implement abstraction using the above two features provided by
access specifiers. Say, the members that define the internal implementation can be
marked as private in a class. And the important information needed to be given to
the outside world can be marked as public. And these public members can access
the private members as they are inside the class.
INHERITANCE
• The capability of a class to derive properties and characteristics from
another class is called Inheritance. Inheritance is one of the most
important features of Object-Oriented Programming.
• Inheritance is a feature or a process in which, new classes are created
from the existing classes. The new class created is called “derived class” or
“child class” and the existing class is known as the “base class” or “parent
class”. The derived class now is said to be inherited from the base class.
• When we say derived class inherits the base class, it means, the derived
class inherits all the properties of the base class, without changing the
properties of base class and may add new features to its own. These new
features in the derived class will not affect the base class. The derived
class is the specialized class for the base class.
• Sub Class: The class that inherits properties from another class is called
Subclass or Derived Class.
• Super Class: The class whose properties are inherited by a subclass is
called Base Class or Superclass.
• Why and when to use inheritance?
• Consider a group of vehicles. You need to create classes
for Bus, Car, and Truck. The methods fuelAmount(),
capacity(), applyBrakes() will be the same for all three
classes.
• If we create these classes avoiding inheritance then we
have to write all of these functions in each of the three
classes as shown below figure:
• You can clearly see that the above process results in
duplication of the same code 3 times. This increases the
chances of error and data redundancy. To avoid this type of
situation, inheritance is used.
• If we create a class Vehicle and write these three functions
in it and inherit the rest of the classes from the vehicle
class, then we can simply avoid the duplication of data and
increase re-usability. Look at the below diagram in which
the three classes are inherited from vehicle class:
• Using inheritance, we have to write the functions only one
time instead of three times as we have inherited the rest of
the three classes from the base class (Vehicle).
Implementing inheritance in C++: For creating a sub-class
that is inherited from the base class we have to follow the
below syntax.
• Derived Classes: A Derived class is defined as the class
derived from the base class.
Syntax:
• class <derived_class_name> : <access-specifier>
<base_class_name> { //body }Where
class — keyword to create a new class
derived_class_name — name of the new class, which will
inherit the base class
access-specifier — either of private, public or protected. If
neither is specified, PRIVATE is taken as default
base-class-name — name of the base class
Note: A derived class doesn’t inherit access to private data
members. However, it does inherit a full parent object, which
contains any private members which that class declares.
• Example:
1. class ABC : private XYZ //private derivation
{ }
2. class ABC : public XYZ //public derivation
{ }
3. class ABC : protected XYZ //protected derivation
{ }
4. class ABC: XYZ //private derivation by default
{ }
Note:
• When a base class is privately inherited by the derived class, public
members of the base class becomes the private members of the
derived class and therefore, the public members of the base class
can only be accessed by the member functions of the derived class.
They are inaccessible to the objects of the derived class.
• On the other hand, when the base class is publicly inherited by the
derived class, public members of the base class also become the
public members of the derived class.
• Therefore, the public members of the base class are accessible by
the objects of the derived class as well as by the member functions
of the derived class.
• Modes of Inheritance: There are 3 modes of inheritance.
• Public Mode: If we derive a subclass from a public base
class. Then the public member of the base class will
become public in the derived class and protected members
of the base class will become protected in the derived class.
• Protected Mode: If we derive a subclass from a Protected
base class. Then both public members and protected
members of the base class will become protected in the
derived class.
• Private Mode: If we derive a subclass from a Private base
class. Then both public members and protected members
of the base class will become Private in the derived class.
• Note: The private members in the base class cannot be
directly accessed in the derived class, while protected
members can be directly accessed. For example, Classes B,
C, and D all contain the variables x, y, and z in the below
example. It is just a question of access.
Access specifiers in C++
• In class, we have an option to make our data public, private, and
protected. This can be done with the help of access specifiers like
public, private, and protected. We can change the access specifier
according to our needs and data. Using these access specifiers, the
programmer gets control over data visibility. That means a
programmer can decide what functions or data should be kept hidden
and what to show to the user.
• NOTE: By default(if not declared), all the items in a class are private.
• Public: The data Members/member functions declared as public can
be accessed by the same class and other classes.
• Private: The data Members/member functions declared as private can
be accessed by the same class only. Data cannot be accessed outside
the class. If accessed, it will give an error.
• Protected: The data Members/member functions declared as private
can be accessed by the same class and the derived class.
Types Of Inheritance:-
• Single inheritance
• Multilevel inheritance
• Multiple inheritance
• Hierarchical inheritance
• Hybrid inheritance
Types of Inheritance in C++
1. Single Inheritance: In single inheritance, a class is allowed to
inherit from only one class. i.e. one subclass is inherited by one
base class only.

Syntax:
class subclass_name : access_mode base_class { // body of
subclass }; OR class A { ... .. ... }; class B: public A { ... .. ... };
• 2. Multiple Inheritance: Multiple Inheritance
is a feature of C++ where a class can inherit
from more than one class. i.e one subclass is
inherited from more than one base class.
• 3. Multilevel Inheritance: In this type of inheritance, a
derived class is created from another derived class.
• class C { ... .. ... }; class B:public C { ... .. ... }; class A:
public B { ... ... ... };
• 4. Hierarchical Inheritance: In this type of inheritance,
more than one subclass is inherited from a single base
class. i.e. more than one derived class is created from a
single base class.

Syntax:-
• class A { // body of the class A. }
• class B : public A { // body of class B. }
• class C : public A { // body of class C. }
• class D : public A { // body of class D. }
• 5. Hybrid (Virtual) Inheritance: Hybrid Inheritance
is implemented by combining more than one type
of inheritance.
• For example: Combining Hierarchical inheritance
and Multiple Inheritance.
Below image shows the combination of hierarchical
and multiple inheritances:
• 6. A special case of hybrid inheritance:
Multipath inheritance:
A derived class with two base classes and these
two base classes have one common base class is
called multipath inheritance. Ambiguity can arise
in this type of inheritance. There are 2 Ways to
Avoid this Ambiguity:
• 1) Avoiding ambiguity using the scope resolution
operator: Using the scope resolution operator we
can manually specify the path from which data
member a will be accessed
• 2) Avoiding ambiguity using the virtual base
class
DATA HIDING
• Data is the most confidential and sensitive information
that must be kept safe and protected against unwarranted
disclosure from all outsiders unless they have permission to
access it.
• Data hiding is an object-oriented programming technique
for protecting the data within a class from unwanted
access and preventing unneeded intrusion from outside the
class. It helps in hiding internal object details, i.e., data
members within the class to prevent its direct access from
outside the class. Data hiding is also known as Information
hiding
• Data hiding guarantees the restricted access of data from
unwanted sources and maintains data integrity by
preventing unintended or intended changes.
• The term "data hiding" refers to the process
of concealing or hiding the data from program
components that don't need to be retrieved. Data
hiding helps in the protection of a class's members.
• The data members and the member functions in a
class are made private using data hiding so that they
cannot be accessed falsely by functions outside the
class and are protected from accidental modifications
and changes. This helps in providing object integrity
and in preventing unintended or intended changes.
• Let's take one example to
understand the concept of
data hiding:
• Suppose, there is a
class A having a
variable var and two
functions, one to input the
number from the user and
the other to display the
variable entered by the user
on the screen. Here, we will
declare the variable "var" as
private so, that it can be
accessed only by the
members of the same class,
and it can't be accessed
anywhere else. Hence, we
will be unable to access this
variable outside the class,
which is called data hiding.
• Applications of Data Hiding
• It helps in protecting sensitive information against
unwarranted disclosure from all outsiders unless they have
permission to access it.
• It helps in isolating the objects as the basic concept of
object-oriented programming, which means that objects
within the class are disconnected from irrelevant data.
• It helps in increasing the data security against hackers
which helps in ensuring that they are unable to access
confidential data.
• It helps to prevent damage to volatile and sensitive data by
hiding it from the public.
Benefits of Data Hiding
• Benefits of data hiding includes:
• Increased data protection and security against hackers.
• It ensures data assurance from corruption and unwarranted access.
• It is used to minimize data complexity.
• It increases the program’s reusability.
• It helps in defining the interface clearly and improves readability
and comprehensibility.
• It reduces system complexity and increases robustness by limiting
interdependencies between software components.
Disadvantages of Data Hiding
• The disadvantage of data hiding in c++ is that it requires additional
coding in order to achieve the desired effect in hidden data. This
makes the code lengthier. So, data hiding can be a harder process
for a programmer, and he may need to write lengthy codes to
create effects in the hidden data.
• The link between the visible and invisible data makes the objects
work faster, but data hiding prevents this linkage, and so the
process becomes slow.
Access Specifiers
• To support the features of data hiding in
c++, abstraction, and encapsulation in object-oriented
programming, we have the concept of access
specifiers.
• The access restriction to the class member functions is
specified by access modifiers.
• Access modifiers are also known as visibility modes in
C++, and there are three types of visibility modes:
public, private, and protected.
• Access specifiers are mainly used for data hiding in c++
and encapsulation as they can help us to control what
part of a program can access the members of a class.
So that misuse of data can be prevented.
• Public Visibility Mode:
• In public visibility mode, when we inherit a child
class from the parent class, then the public,
private, and protected members of the base class
remain public, private, and protected members
respectively in the derived class as well.
• The public visibility mode retains the accessibility
of all the members of the parent class.
• The public members of the parent class are
accessible by the child's class and all other
classes.
• The protected members of the base class are
accessible only inside the derived class and
its inherited classes.
• However, the private members are not accessible
to the child class.
• The syntax of using Visibility Modes is:
class child_class_name :: visibility_mode parent_class_name
{
}
The visibility_mode can be public, private or protected.
• Let's see an example to understand the concept of public visibility
mode:
class Parent
{ The protected variable x2 will be inherited
private: from the Parent class and will be accessible in
int x1; the Child class, similarly, the public
variable x3 will be inherited from the Parent
protected: class and will be accessible in the Child class,
but the private variable x1 will not be
int x2; accessible in the Child class.

public:
int x3;
};
class Child: public Parent
{

};
• Private Visibility Mode:
• In the private visibility mode, when we inherit a
child class from the parent class, then all the
members (public, private and protected
members) of the base class will
become private in the derived class.
• The access of these members outside the derived
class is restricted and they can only be accessed
by the member functions of the derived class.
Let's see an example to understand the concept of private visibility mode:
class Parent
{
private:
int x1; As the visibility mode is private, so, all the
members of the base class have become
protected: private in the derived class. The error is thrown
int x2; when the object of the derived class tries to
access these members outside the derived
public: class.
int x3;
};
class Child: private Parent
{

};
• Protected Visibility Mode:
• In the protected visibility mode, when we inherit
a child class from the parent class, then all the
members of the base class will become
the protected members of the derived class.
• Because of this, these members are now only
accessible by the derived class and its member
functions. These members can also be inherited
and will be accessible to the inherited subclasses
of this derived class.
Let's see an example to understand the concept of protected visibility mode:
class Parent
{
private:
int x1;
As the visibility mode is protected, the
protected: protected and the public members of the
int x2; Parent class become the protected members
of the Child class.
public: The protected variable x2 will be inherited
int x3; from the Parent class and will be accessible in
}; the Child class, similarly, the public
class Child: protected Parent variable x3 will be inherited from the parent
{ class as the protected member and will be
accessible in the Child class, but the private
}; variable x1 will not be accessible in the Child
class.
SUMMARY
 Data hiding is an object-oriented programming technique for protecting the
data within a class from unwanted access and preventing unneeded intrusion from
outside the class.
 Data abstraction is the process of providing only the essential details to the
outside world and hiding the internal complex details.
 Data encapsulation is the process of wrapping or bundling the data members and
member functions into a single unit as a capsule known as a class.
 Access specifiers are used to provide access restrictions to the class member
functions. There are three access specifiers: public, private, and protected.
 When the members in the class are declared as public, then they are accessible
from anywhere.
 When the members in the class are declared private, then, they are only accessible
by the members of the base class.
 When the members in the class are declared as protected, then, they are
accessible in the base class and the derived classes.
 Private access specifier provides more security to its data members as compared
to the public and protected access specifier.
 Access modifiers are mainly used for data hiding in c++ and encapsulation as they
can help us to control what part of a program can access the members of a class.
So that misuse of data can be prevented.
POLYMORPHISM
• Polymorphism means one thing has different forms.
Polymorphism allows a member function of a class to
behave differently based on the object that will call it.
Polymorphism occurs when classes are related through
inheritance.
• You can take an example:
• Suppose there is a function playInstrument() in parent class
“Instrument” and Instrument class have two child classes or
sub-classes: “Guitar“ and “Trumpet” and playInstrument
will return the sound produced by the instrument which
will call that function. So if the Guitar class object will call
playInstrument then Guitar sound will be the output and if
the Trumpet class object will call playInstrument then
Trumpet sound will be the output.
• Polymorphism can be achieved through function overloading and
function overriding.
Function overriding: In function overriding child class can exhibit
different implementation of the same function which has been
defined in parent class also, according to its usages.
• The above example of “Instrument” class is an example of Function
overriding.
Function overloading: Polymorphism is also achieved through function
overloading. In function overloading, methods can have the same
name but the number of arguments is different in function calls.
Results will be different according to the number of arguments with
which the function is called.
• You can take a real-life example. Suppose you created a function to
calculate areas of a figure to calculate the area of rectangle and
square. As you know rectangle area is lengthbreadth and square’s
area is sideside so rectangle area function should take 2 arguments
length and breadth whereas square area will take one argument
that is side.
• So instead of creating functions with separate names, you can
create two functions with the same name but the number of
arguments is different for both functions.
//1- for square
int Findarea(int side) findArea(3) call will go to 1 function as the
number of arguments in function is one and
{ findArea(2,5) call will go to 2 function as the
number of arguments in the function call is
return side * side; two. This is the concept of function
overloading.
}

//for rectangle
int Findarea(int length, int breadth) {
return length * breadth;
}
FUNDAMENTAL DATA TYPES
• In C++, every variable use data types to define the type of
data it can store.
• As, we already know variables are something which stores
data. So, data types are used to specify before the
compilation that what type of data the variable is going to
store.
• C++ is said to be stongly typed language which actually
means we have to define the data type of the variable
before using it.Each data type has its own size in memory.
• There are mainly two types of data types in C++:-
 Fundamental data types
 User defined data types
Fundamental Data types
• Fundamental data types are the data types which
are predefined in the language and can be
directly used to declare a variable in C++.
• The various fundamental data types are:
 char (Character)
 int (Integer)
 float (Floating point)
 bool (Boolean)
 double (Double floating point)
 void (valueless)
1. Character
• It is the datatype that is used to store
characters like a,b,c etc.
• To define Character in C++ we
use char keyword.
• Size of char datatype is 1 byte i.e 8 bits.
• It's range is from -128 to 127 or it can be 0-
255.
Syntax:-
• char a;
• where 'a' is variable.
2. Integer
• It is the datatype that is used to store integer values like 1,2,-1 etc.
• To define Integer in C++ we use int keyword.
• Size of int datatype is 4 byte i.e 32 bits.
• It's range is from -2147483648 to 2147483647.
• Syntax:-
• int a;

3. Floating point
• It is the datatype that is used to store floating values or decimal
values like 1.1,2.1 etc.
• To define Floating point in C++ we use float keyword.
• Size of float datatype is 4 byte i.e 32 bits.
• It's range is from +/- 3.4e +/- 38 (~7 digits).
• Syntax:-
• float a;
4. Boolean
• It is the datatype that is used to store two values only i.e true or
false.
• To define Boolean in C++ we use bool keyword.
• Size of bool datatype is 1 byte i.e 8 bits.
• Syntax:-
• bool a;

5. Double floating point


• It is the datatype that is used to store floating values with higher
precision.
• To define Double Floating Point in C++ we use float keyword.
• Size of double datatype is 4 byte i.e 32 bits.
• It's range is from +/- 1.7e +/- 308 (~15 digits).
• Syntax:-
• double a;
• 6. Valueless
• It is the datatype that is used to represent a variable without any value.
• To define Valueless in C++ we use void keyword.
• Void can be used as an return type of functions which indicates that
function is returning nothing.
• Syntax:-
void a;
• A simple use of void as a return type of a function in C++:
void printmsg(void)
{
printf("Hello world\n");
}

• Here the return type of function printmsg is void which means it is


returning nothing.
• void inside the parenthesis shows that the function has no or valueless
arguement.
Data type modifiers
• As the name suggests ,these are used to modify primitive data type i.e int,char,float.
• They are used as a prefix to the primitive data types.
• These modifiers change the size and the type of values that a primitive data type can hold.
• There are four modifiers:
signed:- It is used to represent numbers both in the positive and negative ranges.
Syntax:
• signed int a;
• "a" can hold both negative and positive values.
unsigned:- It is used to represent numbers in the positive only.
• Syntax:
• unsigned int b;
• "b" can hold only positive values no negative values.
short:- It is used to decrease the size of primitive data types.
• Syntax:
• short int c;
• "c" will now take 2 bytes of memory instead of 4 bytes.
long:- It is used to increase the size of primitive data types.
• Syntax:
• long int d;
Literals
• Literals are the Constant values that are assigned to the constant
variables. Literals represent fixed values that cannot be modified. Literals
contain memory but they do not have references as variables. Generally,
both terms, constants, and literals are used interchangeably.
• Literals are data used for representing fixed values. They can be used
directly in the code. For example: 1, 2.5, 'c' etc.
• Here, 1, 2.5 and 'c' are literals. Why? You cannot assign different values to
these terms.
• For example, “const int = 5;“, is a constant expression and the value 5 is
referred to as a constant integer literal. There are 4 types of literal in C and
five types of literal in C++.
 Integer literal
 Float literal
 Character literal
 String literal
• 1. Integers
• An integer is a numeric literal(associated with
numbers) without any fractional or exponential
part. There are three types of integer literals in C
programming:
• decimal (base 10)
• octal (base 8)
• hexadecimal (base 16)
• For example:
• Decimal: 0, -9, 22 etc Octal: 021, 077, 033 etc
Hexadecimal: 0x7f, 0x2a, 0x521 etc In C++
programming, octal starts with a 0, and
hexadecimal starts with a 0x.
2. Floating-point Literals
• A floating-point literal is a numeric literal that has
either a fractional form or an exponent form. For
example:
• -2.0
• 0.0000234
• -0.22E-5
• Note: E-5 = 10-5
3. Characters
• A character literal is created by enclosing a single
character inside single quotation marks. For
example: 'a', 'm', 'F', '2', '}' etc.
4. Escape Sequences
• Sometimes, it is necessary to use characters that
cannot be typed or has special meaning in C++
programming. For example, newline (enter), tab,
question mark, etc.
• In order to use these characters, escape
sequences are used. \b Backspace, \n New line,
\0 null character
5. String Literals
• A string literal is a sequence of characters
enclosed in double-quote marks. For example:
• "good” string constant, “ “null string constant,
"x"string constant having a single character
C++ Constants
• In C++, we can create variables whose value
cannot be changed. For that, we use
the const keyword. Here's an example:
const int LIGHT_SPEED = 299792458;
LIGHT_SPEED = 2500 // Error! LIGHT_SPEED is a constant.
• Here, we have used the keyword const to declare
a constant named LIGHT_SPEED. If we try to
change the value of LIGHT_SPEED, we will get an
error.
• A constant can also be created using
the #define preprocessor directive. We will learn
about it in detail in the C++ Macros tutorial.
C++ Variables
• In programming, a variable is a container (storage area) to
hold data.
• To indicate the storage area, each variable should be given
a unique name (identifier). For example,
• int age = 14; Here, age is a variable of the int data type, and
we have assigned an integer value 14 to it.
• Note: The int data type suggests that the variable can only
hold integers. Similarly, we can use the double data type if
we have to store decimals and exponentials.
• The value of a variable can be changed, hence the
name variable.
• int age = 14; // age is 14
• age = 17; // age is 17
• Rules for naming a variable
• A variable name can only have alphabets, numbers,
and the underscore _.
• A variable name cannot begin with a number.
• It is a preferred practice to begin variable names with a
lowercase character. For example, name is preferable
to Name.
• A variable name cannot be a keyword. For
example, int is a keyword that is used to denote
integers.
• A variable name can start with an underscore.
However, it's not considered a good practice.
• Note: We should try to give meaningful names to
variables. For example, first_name is a better variable
name than fn.
C++ Operators
• Operators are symbols that perform operations on
variables and values. For example, + is an operator
used for addition, while - is an operator used for
subtraction.
• Operators in C++ can be classified into 6 types:
1. Arithmetic Operators
2. Assignment Operators
3. Relational Operators
4. Logical Operators
5. Bitwise Operators
6. Other Operators
• 1. C++ Arithmetic Operators
• Arithmetic operators are used to perform
arithmetic operations on variables and data.
For example,
• a + b;
• Here, the + operator is used to add two
variables a and b. Similarly there are various
other arithmetic operators in C++.
• + for addition, - for subtraction, etc.
/ Division Operator
Example 1: Arithmetic Operators Note the operation (a / b) in our program.
The / operator is the division operator.
As we can see from the above example, if an
#include <iostream>
integer is divided by another integer, we will get
using namespace std;
the quotient. However, if either divisor or dividend
int main() { is a floating-point number, we will get the result in
int a, b; decimals.
In C++,
a = 7;
7/2 is 3
b = 2; 7.0 / 2 is 3.5
7 / 2.0 is 3.5
// printing the sum of a and b 7.0 / 2.0 is 3.5
cout << "a + b = " << (a + b) << endl;

// printing the difference of a and b % Modulo Operator


cout << "a - b = " << (a - b) << endl; The modulo operator % computes the remainder. When a =
9 is divided by b = 4, the remainder is 1.
// printing the product of a and b Note: The % operator can only be used with integers.
cout << "a * b = " << (a * b) << endl;
Increment and Decrement Operators
// printing the division of a by b C++ also provides increment and decrement operators: ++ and --
cout << "a / b = " << (a / b) << endl; respectively.
•++ increases the value of the operand by 1
// printing the modulo of a by b •-- decreases it by 1
cout << "a % b = " << (a % b) << endl;
For example,
int num = 5; // increment operator ++num; // 6
return 0;
}
Here, the code ++num; increases the value of num by 1.

Output
a + b = 9 a - b = 5 a * b = 14 a / b = 3 a % b = 1
2. C++ Assignment Operators
• In C++, assignment operators are used to assign values to
variables. For example,
• // assign 5 to a a = 5;Here, we have assigned a value of 5 to
the variable a.
#include <iostream>
using namespace std;

int main() {
int a, b;

// 2 is assigned to a
a = 2;

// 7 is assigned to b
b = 7;

cout << "a = " << a << endl;


cout << "b = " << b << endl;
cout << "\nAfter a += b;" << endl;

// assigning the sum of a and b to a


a += b; // a = a +b
cout << "a = " << a << endl;

return 0;
}
• 3. C++ Relational Operators
• A relational operator is used to check the relationship between two operands. For
example,
// checks if a is greater than b
a > b;
• Here, > is a relational operator. It checks if a is greater than b or not.
• If the relation is true, it returns 1 whereas if the relation is false, it returns 0.
#include <iostream>
using namespace std;

int main() {
int a, b;
a = 3;
b = 5;
bool result;

result = (a == b); // false


cout << "3 == 5 is " << result << endl;

result = (a != b); // true


cout << "3 != 5 is " << result << endl;

result = a > b; // false


cout << "3 > 5 is " << result << endl;

result = a < b; // true


cout << "3 < 5 is " << result << endl;

result = a >= b; // false


cout << "3 >= 5 is " << result << endl;

result = a <= b; // true


cout << "3 <= 5 is " << result << endl;

return 0;
}
4. C++ Logical Operators
• Logical operators are used to check whether an expression
is true or false. If the expression is true, it returns 1 whereas if
the expression is false, it returns 0.

Suppose,
a = 5 b = 8

Then, (a > 3) && (b > 5) evaluates to true


(a > 3) && (b < 5) evaluates to false

(a > 3) || (b > 5) evaluates to true


(a > 3) || (b < 5) evaluates to true
(a < 3) || (b < 5) evaluates to false

!(a < 3) evaluates to true


!(a > 3) evaluates to false
Explanation of logical operator program
 (3 != 5) && (3 < 5) evaluates to 1 because both operands (3 != 5) and (3 < 5) are 1 (true).
 (3 == 5) && (3 < 5) evaluates to 0 because the operand (3 == 5) is 0 (false).
 (3 == 5) && (3 > 5) evaluates to 0 because both operands (3 == 5) and (3 > 5) are 0 (false).
 (3 != 5) || (3 < 5) evaluates to 1 because both operands (3 != 5) and (3 < 5) are 1 (true).
 (3 != 5) || (3 > 5) evaluates to 1 because the operand (3 != 5) is 1 (true).
 (3 == 5) || (3 > 5) evaluates to 0 because both operands (3 == 5) and (3 > 5) are 0 (false).
 !(5 == 2) evaluates to 1 because the operand (5 == 2) is 0 (false).
 !(5 == 5) evaluates to 0 because the operand (5 == 5) is 1 (true).
• 5. C++ Bitwise Operators
• In C++, bitwise operators are used to perform
operations on individual bits. They can only be
used alongside char and int data types.
• 6. Other C++ Operators
• Here's a list of some other common operators
available in C++.
ARRAYS
• An array in C/C++ or be it in any programming language is a collection of similar
data items stored at contiguous memory locations and elements can be accessed
randomly using indices of an array. They can be used to store the collection of
primitive data types such as int, float, double, char, etc of any particular type. To
add to it, an array in C/C++ can store derived data types such as structures,
pointers etc. Given below is the picture representation of an array.

• Why do we need arrays?


We can use normal variables (v1, v2, v3, ..) when we have a small number of
objects, but if we want to store a large number of instances, it becomes difficult to
manage them with normal variables. The idea of an array is to represent many
instances in one variable.
• Advantages:-
• Code Optimization: we can retrieve or sort the data efficiently.
• Random access: We can get any data located at an index position.

• Disadvantages:-
• Size Limit: We can store only the fixed size of elements in the array. It doesn’t grow
its size at runtime.
CONTROL FLOW IN OOPS
• 1. Branching or Conditional Structure –
• In the normal state, execution of the program is
gradual execution. When the Sequential
Execution of the program is blocked by the
selected Statements, it is called Branches
Execution.
• Control of the program requires a condition to
block selected statements. That is, the control of
the program is done by blocking the selected
statements based on a condition, then the
statement used in it is called Conditional
Statement.
• C ++ consists of three Conditional Statements –
• 2. Iterative or looping Structure –
• Looping or Reversible Statement Program sometimes requires the
same statement to be used repeatedly, for this C ++ has three
methods.
• Using which we can execute statements repeatedly which are the
following are also called Looping Statements.
• Through loops, we can execute anyone’s statement or many
abstract statements more than once until the condition is achieved.
• 1. While loop –
• while loop is an entry-controlled loop. In this, the
statement keeps executing continuously until a
condition is true. It first checks the condition and later
executes the statement.
• It is necessary to initialize the variable in While Loop.
• If while Loop is to be repeated, the
increment/decrement operator is used.
• Repeats until the condition in While Loop is true.
• syntax:-
while(condition)
{
statement1;
statement2;
————-
}
2. Do while loop –
• This loop is exit-controlled. This loop is also like a while
loop but it executes the first statement and checks the
condition later.
• Repeats until the condition in Do-While Loop is true.
• The specialty of Do-While is that, even if the condition is
false, it prints a statement in the output.
• This loop ensures that the program is executed at least
once.
• syntax:-
do
{
Statement1;
Statement2;
————–
}
While (condition);
• 3. For loop –
• For Loop only needs a Variable Declaration. Except for this
statement, he does all the work inside himself.
• Repeats until the condition in While Loop is true.
• This is an entry controlled loop. In this, the statement is
executed until the condition becomes true. This loop
consists of three components initialization statement,
Boolean statement, and increment/decrement statement.
• syntax:-
for(initial condition, test condition; incrementor or
decrement)
{
statement1;
statement2;
}
• 4. Nested loop –
• Nested loop in C ++ Programming is not a type of
loop. Here, in a program, you use the same loop
two or more times, it is called a nested loop.
• For loop is used in this program. If you want, you
can also use the if, while, switch case. It has no
syntax, it depends on writing your program.
• while loops are executed only. As the name
suggests, another loop can be executed inside a
loop.
• 3. Sequential Control Flow Structure –
• The statements written in the program are
implemented one after the other.
• The statements are executed in the order in which the
compiler is received.
• This execution of the program is called serial execution.
• Jump statements –
• Jump statements are used to interrupt the normal
flow of program.
• 1. Break statement –
• This statement is used to end a sequence of statements in a switch
statement and to immediately exit a loop.
• The execution of the loops and switch cases of the Break Statement
Program stops at any condition.
• syntax:- break;
• #include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 10; i++)
{
if (i == 5)
{
break;
}
cout<<i<<“\n”;
}
}
• 2. Continue statement –
• The continue statement is used when we want to run the loop
continues with the next iteration and skip other statements in the
loop for the current iteration.
• Depending on the condition of the loops of the Continue Statement
program, skip the middle statements, and execute the subsequent
statements.
• syntax:- continue;
• #include <iostream>
using namespace std;
int main()
{
for(int i=1;i<=10;i++){
if(i==5){
continue;
}
cout<<i<<“\n”;
}
}
3. Go to statement –
• Go to is the statement of C ++ Programming. Labels are used in this.
• There are two types of Go to Statements.
• Forward
• Backward
• When a goto statement executes its next statement except for some statement, it
is called Forward goto statement and goes to its previous label to execute any
previous or executed statement again, it is called Backward goto statement.

Syntax for Forward and Backward goto Statement

Syntax for Forward


• goto label ;
statement ;
———–
label ;
Syntax for Backward
• label ;
statement ;
———–
goto label ;
• #include <iostream>
using namespace std;
int main()
{
int num; cout<<“Enter a number: “;
cin>>num;
if (num % 2==0){
goto print;
}
else {
cout<<“Odd Number”;
}
print:
cout<<“Even Number”;
return 0;
}
• 1. What are the control statements in C++?
• Control statements are elements in the source code that control the flow
of program execution.
• 2. What is Compound Statement?
• A compound statement is a grouping of statements in which each
statement ends with a semi-colon. The group of statements is called a
block.
Compound statements are enclosed between the pair of braces ( { } ). The
opening brace( { )
signifies the beginning and closing brace ( } ) signifies the end of the block.
• 3. What is the Null Statement?
• Writing only a semicolon indicates a null statement. Thus ‘;’ is a null or
empty statement.
This is quite useful when the syntax of the language needs to specify a
statement but the logic of the program does not need any statement. This
statement is generally used for and while looping statements.
• 4. What is Branching or Conditional Structure?
• We can control the flow of a program using branching and looping
statements. Branching statements give us code that is optionally
executable, depending on the outcome of certain tests which that we can
define.
• 5. What is the loop statement?
• A loop statement allows us to execute a statement or group
of statements multiple times and following is the general
form of a loop statement in most of the programming
languages − C++ programming language provides the
following type of loops to handle looping requirements.
• 6. What is a sequential statement?
• Sequential statements are. assignment statements that
assign values to variables and signals. flow control
statements that conditionally execute statements (if and
case), repeat statements (for…loop), and skip statements
(next and exit).
COMPILATION AND EXECUTION OF
PROCESS
• Run your Hello World C++ program locally using the Terminal,
Command Prompt, or Visual Studio Code.
• The Process
• C++ is a compiled language. That means that to get a program to
run, you must first translate it from the human-readable form to
something a machine can “understand.” That translation is done by
a program called a compiler.
• What you read and write is called source code (usually it’s in an
English-like language like C++), and what the computer executes is
called executable, object code, or machine code (a machine
language).
• Typically C++ source code files are given the suffix:
 .cpp (ex: hello.cpp) or
 .h (ex: std_lib_facilities.h).
• Compile:
• g++ hello.cpp -o helloA compiler translates the C++ program into
machine language code which it stores on the disk as a file with the
extension .o (e.g. hello.o). A linker then links the object code with
standard library routines that the program may use and creates an
executable image which is also saved on disk, usually as a file with
the file name without any extension (e.g. hello).
• Execute:
• ./helloThe executable is loaded from the disk to memory and the
computer’s CPU (Central Processing Unit) executes the program
one instruction at a time.
• Running Hello World Locally:
• On the Mac, it’s called the Terminal. On Windows, it’s called the
Command Prompt.
Execution of C++ program:
For creating and executing a C++ program, one must follow four important steps.

(1) Creating Source code


Creating includes typing and editing the valid C++ code as per the rules followed by the C++ Compiler.
(2) Saving source code with extension .cpp
After typing, the source code should be saved with the extension .cpp
(3) Compilation
This is an important step in constructing a program. In compilation, compiler links the library files
with the source code and verifies each and every line of code. If any mistake or error is found, it will
inform you to make corrections. If there are no errors, it translates the source code into machine
readable object file with an extension .obj
(4) execution
This is the final step of construction of a C++ Program. In this stage, the object file becomes an
executable file with extension .exe. Once the program becomes an executable file, the program has
an independent existence. This means, you can run your application without the help of any
compiler or IDE.
REFERENCE VS. POINTER VARIABLE
• A pointer in C++ is a variable that holds the memory
address of another variable.
• A reference is an alias for an already existing variable. Once
a reference is initialized to a variable, it cannot be changed
to refer to another variable.
Memory Organization of Class
• In C++, we can efficiently allocate the memory at runtime and deallocate it
when not required. With this feature, we get the flexibility of allocation
and deallocation of memory as per requirement.
What Is C++ Memory Management?
• Memory management can be defined as a process in which management
of a computer’s memory occurs, for example assigning memory to
programs, variables etc., in such a way that it doesn’t affect the overall
performance. Sometimes, the computer’s data can range up to terabytes,
so efficient use of memory is necessary to minimize memory wastage and
boost up performance.
Why Do We Need Memory Management, and How Does It Work?
• Memory management is required to ensure that there is no wastage of
memory and that allocation takes place efficiently. The memory that a C++
program uses is divided into different parts. Here, we will discuss two, i.e.
stack and heap.
• Stack: In stack, all the variables that are declared inside the function and
other information related to the function are stored.
• Heap: Heap is unused memory and the part from where the memory is
allocated dynamically when the program runs.
• During the declaration of an array, there are times when
the correct memory is not determined until runtime.
• To avoid such scenarios, we usually declare an array of the
maximum size.
• However, because of this full size, some memory remains
unused. For example, let us suppose we have declared an
array of size 30, and after declaring the array, it turns out
that we only need space of 10 size, so the rest of the space
is of no use, or we can say it will get wasted.
• To avoid such cases, we use memory allocation. We can
allocate the memory at runtime from the heap using an
operator.
• Memory allocation is the process of setting aside sections of
memory in a program to be used to store variables, and instances of
structures and classes. There are two basic types of memory
allocation:
When you declare a variable or an
instance of a structure or class. The
memory for that object is allocated by
the operating system. The name you
declare for the object can then be used
to access that block of memory.

When you use dynamic memory allocation


you have the operating system designate a
block of memory of the appropriate size
while the program is running. This is done
either with the new operator or with a call
to the malloc function. The block of memory
is allocated and a pointer to the block is
returned. This is then stored in a pointer to
the appropriate data type.
• The Heap
• The Heap is that portion of computer memory, allocated to a running application, where
memory can be allocated for variables, class instances, etc. From a program's heap the OS
allocates memory for dynamic use. Given a pointer to any one of the allocated blocks the OS
can search in either direction to locate a block big enough to fill a dynamic memory allocation
request.
Blocks of memory allocated on the heap are actually a special type of data structure
consisting of (1) A pointer to the end of the previous block, (2) a pointer to the end of this
block, (3) the allocated block of memory which can vary in size depending on its use, (4) a
pointer to the beginning of this block, and (5) a pointer to the next block.
• Depending on the type of operating system there are two possible algorithms that can be
implemented in order to locate a block of memory in the heap to allocate:
• First-Fit - The needed amount of memory is allocated in the first block located in the heap
that is big enough. This is faster but can result in greater fragmentation* of the heap.
• Best-Fit - All of the heap is searched and the needed amount of memory is allocated in the
block where there is the least amount of memory left over. Slower but can result in less
fragmentation*.

The Heap Layout.


Blank spaces between allocated blocks are where previously used blocks have been deallocated.
Garbage Collection in C++
• Garbage collection is a memory management technique. It is a separate automatic
memory management method which is used in programming languages where
manual memory management is not preferred or done.
• In the manual memory management method, the user is required to mention the
memory which is in use and which can be deallocated, whereas the garbage
collector collects the memory which is occupied by variables or objects which are
no more in use in the program.
• Only memory will be managed by garbage collectors, other resources such as
destructors, user interaction window or files will not be handled by the garbage
collector.
• Few languages need garbage collectors as part of the language for good efficiency.
These languages are called as garbage-collected languages. For example, Java, C#
and most of the scripting languages needs garbage collection as part of their
functioning.
• Whereas languages such as C and C++ support manual memory management
which works similar to the garbage collector.
• There are few languages that support both garbage collection and manually
managed memory allocation/deallocation and in such cases, a separate heap of
memory will be allocated to the garbage collector and manual memory.
• Dynamically allocated memory during run time from the heap needs to be
released once we stop using that memory. Dynamically allocated memory takes
memory from the heap, which is a free store of memory.
• In C++ this memory allocation and deallocation are done manually using
commands like new, delete. Using ‘new’ memory is allocated from the heap. After
its usage, this memory must be cleared using the ‘delete’ command.
• Every memory allocation with ‘new’ must be finished with a ‘delete’ command. If
not we will go out of memory.
• To show it clearly with an example:
• n = new sample_object;
******* usage is implemented here*******
delete n;
• As shown, every new should end or incline with a delete command. Here n pointer
is allocated memory using ‘new’ command and is referenced or pointed to an
object called ‘sample_object’. Once the usage and functioning of the pointer are
completed, we should release or free the memory using the ‘delete’ command as
done above.
• But in case of garbage collection, the memory is allocated using ‘new’ command
but it need not be manually released using ‘delete’. In such cases, the garbage
collector runs periodically checking for free memory. When a piece of memory is
not pointed by any object it clears or releases the memory creating more free
heap space.
• One major disadvantage of garbage collection is the time involved or CPU cycles
involved to find the unused memory and deleting it, even if the user knows which
pointer memory can be released and not in use. Another disadvantage is, we will
not know the time when it is deleted nor when the destructor is called.
• In C++, memory is allocated at run-time,
known as dynamic memory allocation.
Dynamic memory allocation is done through
the new operator.
• In C++, dynamically allocated memory has to
be de-allocated manually by the code author
through the delete operator.
• Otherwise, issues like memory
leakage and dangling pointer occurs. The code
author decides explicitly which memory isn’t
used by the program and needs to be de-
allocated.
new and delete operator
• The new operator is used to dynamically allocate memory
on the heap for an object or an array of objects. And delete
operator is usd to deallocate the memory.
• The new and delete operators are integral parts of every
programming language.
• They allow the programmer to create and delete variables
in the program.
• The use of these operators is essential for creating and
managing different program elements.
• These are also helpful when debugging a program or
removing invalid data from a program.
• A programmer needs to know how to use these operators
effectively to create clean and efficient programs.
• What is the new operator?
• The “new” operator in C++ is used to allocate memory dynamically for a variable or an object at
runtime. This means that the memory is allocated during the execution of the program, as opposed
to being allocated at compile time. When the “new” operator is called, it reserves a block of
memory that is large enough to hold the object being created and then returns a pointer to the first
byte of that memory block.
• Syntax
• Here is the syntax of the new operator in C++ language.
1. Pointer_name=new datatype;
• Here is the syntax to initialize the memory,
• Example

• int *ptr=new int;


2. pointer_variable = new datatype(value);
• Here is the syntax to allocate a block of memory.
• Example

• int *ptr=new int(10);


3. pointer_variable = new datatype[size];
• Example

• int *ptr=new int[];


• This means the pointer will point to the base address of an array
• For example, the following code dynamically allocates memory for an integer and assigns the value
42 to it:
• int *p = new int; //allocate memory for an int
• *p = 42; //assign value 42 to the memory location
Let’s understand it with example.
#include <iostream>
int main()
{
int* pInt = new int; // dynamically allocate memory for an int
*pnt = 5; // store the value 5 in the allocated memory
std::cout << *pnt; // output the value stored in the allocated memory
delete pnt; // deallocate the memory to prevent memory leak
return 0;
}

Output: 5
The new operator is used to dynamically allocate memory for the
variable on the heap, which is a region of memory that remains
allocated until explicitly deallocated using the delete operator. The
pointer pnt is used to access the memory location where the int is
stored.
• What is a delete operator?
• The delete operator is used to deallocate memory that was
previously allocated on the heap using new. It takes a pointer to the
memory to be deallocated as an argument. For example:
• delete p; // Deallocates the memory pointed to by p
• The “delete” operator is used to deallocate memory that the “new”
operator previously allocated. Once a block of memory has been
allocated by “new,” it is important to deallocate it when it is no
longer needed so that other parts of the program can reuse the
memory. The “delete” operator releases the memory back to the
system, and other parts of the program can use it.
• Note: Use delete to deallocate memory allocated with new to avoid
memory leaks.
• Memory leaks occur when the program allocates memory
dynamically but does not deallocate it properly. This causes the
program to consume more memory gradually, eventually leading to
poor performance or even crashing the program.
New and delete operators example

#include <iostream>
int main()
{
int* ptr1 = new int; // dynamically allocate memory for an int
*ptr1 = 5; // store the value 5 in the allocated memory
float *ptr2 = new float(20.324);
int *ptr3 = new int[28];
Output
std::cout << "Value of pointer variable 1 : " << *ptr1<<std::endl;
std::cout << "Value of pointer variable 2 : " << *ptr2<<std::endl;
Value of pointer variable 1 :
if (!ptr3) 5
std::cout << "Allocation of memory failed\n"; Value of pointer variable 2 :
else { 20.324
for (int i = 1; i < 15; i++) Value of store in block of memory:
ptr3[i] = i+1; 2 3 4 5 6 7 8 9 10 11 12 13 14 15 5
std::cout << "Value of store in block of memory: ";
for (int i = 1; i < 15; i++)
std::cout << ptr3[i] << " ";
}
std::cout << *ptr1; // output the value stored in the allocated memory
delete ptr1;// deallocate the memory to prevent memory leak
delete ptr2;
delete ptr3;
return 0;
}
• The first line uses the “new” operator to allocate memory
dynamically for an integer variable and assigns the allocated
memory address to the pointer variable ptr1. The value 5 is stored
in the allocated memory using the pointer variable ptr1.
• The second line uses the new operator to allocate memory for a
float variable dynamically, and assigns the allocated memory
address to the pointer variable ptr2. The value 20.324 is also
assigned to this pointer.
• The third line uses the new operator to dynamically allocate
memory for an array of 28 integers and assigns the allocated
memory address to the pointer variable ptr3.Then the code uses
std::cout to output the values stored in the allocated memory for
the pointer variables ptr1, ptr2, and ptr3.
• In the final lines of the code, the delete operator is used to
deallocate the memory allocated for the pointer variables ptr1,
ptr2, and ptr3 to prevent memory leaks.
• It’s worth noting that in the case of the array (ptr3), the code uses
the if (!ptr3) statement to check if the memory allocation was
successful or not, otherwise it will store values in the array and
output the values stored in the array using a for a loop.
When to do dynamic memory allocation?
• When the size of the data structure needs to change at runtime: For
example, if a program needs to store a large number of items in an
array, and the number of items is not known at compile time,
dynamic memory allocation can be used to create an array of the
appropriate size.
• When working with complex data structures: Dynamic memory
allocation can be used to create linked lists, trees, and other
complex data structures that require a flexible amount of memory.
• When working with polymorphic objects: Dynamic memory
allocation is often used to create objects of different types at
runtime. For example, a program might use dynamic memory
allocation to create objects of different classes inherited from a
common base class.
• When working with large data sets: Dynamic memory allocation can
handle large data sets that cannot fit in the stack memory.
• When memory is being used very efficiently: Dynamic memory
allocation can ensure that the program uses only as much memory
as it needs, rather than allocating a fixed amount of memory at
compile time.
Inline Function
• Inline function in C++ is an enhancement feature that improves the
execution time and speed of the program.
• When an instruction of a function call is encountered during the
compilation of a program, its memory address is stored by the
compiler.
• The function arguments are copied on the stack and after the
execution of the code, the control is transferred to the calling
instruction.
• This process can sometimes cause overhead in function calls,
especially if the function is small and its execution time is less than
the switching time.
• This issue is resolved by using the inline functions.
• These functions overcome the overhead and also make the
program faster by reducing the execution time of the program.
• Following are some key points that you need
to keep in mind while dealing with inline
functions:
• Inline functions that are small have higher
efficiency and better results than the lengthier
inline functions. So, try to keep your inline
functions small in length.
• Although these functions increase the
efficiency of the program and improve its
execution, you should not convert all the
functions into inline functions. If you convert
larger functions to inline, it may lead to code
bloat and reduce the functioning quality of
the program.
• Always try to define large functions outside
the class, since functions defined inside a class
are automatically defined as inline and this
will affect the program negatively. You can use
scope resolution (::) for this purpose.
Syntax of Inline Function in C++
• The syntax for defining the function inline is:
inline return_type function_name(data_type arg1 , data_type
arg2 )
{
// definition of the function
}
Syntax explanation:
• Keyword “inline”: The keyword inline is specified at the
beginning to tell the compiler that the function is an inline
function. However, it’s up to the compiler to decide
whether to inline a function or not.
• Defining the function: An inline function needs to be
defined when it is declared. Whenever there is a call to the
function in the program, the compiler will simply replace it
with the function’s definition.
• When to Use the Inline Function?
• Inline functions are very efficient and can be used in
various areas of a program. But there are some cases
where you can utilize the maximum features of these
functions and extract the maximum output from them.
Some of these cases are:
• Inline functions prove to be the best when it comes to
performance. If you need the performance in your
program, you must go with inline functions as they
enhance the execution time and speed of your
program.
• If you want to hide the implementation details of your
functions, you can define the inline functions outside
the class by using the inline keyword.
• Advantages of Inline Function in C++
• The compilation speed of the program gets increased
since the inline functions prevent function call
overhead.
• Inline functions that are small in length can be used in
embedded systems as well since these functions yield
lesser code than the function call and return.
• These functions also prevent the overhead of function
return calls.
• They allow the compiler to perform some
optimizations on the body of the function that is
content-specific in nature. Such optimizations cannot
take place for other function calls.
• During the invoking or calling of the function, these
functions prevent the overhead of push and pop stack
variables.
• Disadvantages of Inline Function in C++
• Inline functions must be short in length as lengthier inline functions
can cause a reduction of the cache hit rate of the instructions. This
can have adverse effects on the efficiency of the program.
• Excess use of inline functions in the code may lead to the
enlargement of the size of the binary executable code.
• In the case of large functions, compilation overhead can take place
and reduce the efficiency of the code.
• Implementation of these functions in the header files can make
them heavy.
• Since storage is not allocated to such functions and they are stored
in a symbol table, the compiler cannot perform the inlining of these
functions, and hence you can not get the address of these
functions.
• Large inline functions are useless for embedded systems since these
systems give preference to the size of the function over speed.
When the above code is compiled and executed, it produces the following result −
Max (20,10): 20
Max (0,200): 200
Max (100,1010): 1010
Friend function
• A friend function in C++ is defined as a function that can
access private, protected and public members of a class.
• The friend function is declared using the friend keyword
inside the body of the class.
• friend class class_name; // declared in the base class
• Data hiding is a fundamental concept of object-oriented
programming. It restricts the access of private members from
outside of the class.
• Similarly, protected members can only be accessed by derived
classes and are inaccessible from outside. For example,
class MyClass
{ private: int member1;
}
int main()
{
MyClass obj;
// Error! Cannot access private members from here.
obj.member1 = 5; }
However, there is a feature in C++ called friend functions that break this rule and allow us to
access member functions from outside the class.

friend Function in C++


• A friend function can access the private and protected data of a class. We declare a friend
function using the friend keyword inside the body of the class.
class className
{ ... .. ...
friend returnType functionName(arguments);
... .. ...
}
// C++ program to demonstrate the working of friend function

#include <iostream>
using namespace std;

class Distance { Output:


private:
int meter; Distance: 5

// friend function
friend int addFive(Distance);
Here, addFive() is a friend function that can
public:
access both private and public data members.
Distance() : meter(0) {}
Though this example gives us an idea about the
}; concept of a friend function, it doesn't show
any meaningful use.
// friend function definition
int addFive(Distance d) { A more meaningful use would be operating on
objects of two different classes. That's when
//accessing private members from the friend function the friend function can be very helpful.
d.meter += 5;
return d.meter;
}

int main() {
Distance D;
cout << "Distance: " << addFive(D);
return 0;
}
Example 2: Add Members of Two Different Classes
// Add members of two different classes using friend functions
#include <iostream>
using namespace std;
// forward declaration
class ClassB; OUTPUT:
class ClassA {
Sum: 13

public:
// constructor to initialize numA to 12
ClassA() : numA(12) {}

private:
int numA; In this program, ClassA and ClassB have
// friend function declaration declared add() as a friend function. Thus, this
friend int add(ClassA, ClassB); function can access private data of both classes.
}; One thing to notice here is the friend function
class ClassB { inside ClassA is using the ClassB. However, we
public:
haven't defined ClassB at this point.
// constructor to initialize numB to 1
ClassB() : numB(1) {} // inside classA
private: friend int add(ClassA, ClassB);
int numB;
// friend function declaration For this to work, we need a forward declaration
friend int add(ClassA, ClassB); of ClassB in our program.
};
// forward declaration
// access members of both classes class ClassB;
int add(ClassA objectA, ClassB objectB) {
return (objectA.numA + objectB.numB);
}
int main() {
ClassA objectA;
ClassB objectB;
cout << "Sum: " << add(objectA, objectB);
return 0;
}
friend Class in C++
We can also use a friend Class in C++ using the friend keyword. For
example,

class ClassB;
class ClassA
{
// ClassB is a friend class of ClassA friend class ClassB; ... .. ...
}
class ClassB { ... .. ... }

• When a class is declared a friend class, all the member functions of


the friend class become friend functions.
• Since ClassB is a friend class, we can access all members
of ClassA from inside ClassB.
• However, we cannot access members of ClassB from inside ClassA.
It is because friend relation in C++ is only granted, not taken.
Characteristics of a Friend function:
• Some characteristics / features of friend function in C++:
• A global function or a member function of another class, both can
be declared as a friend function.
• A friend function in C++ should not be in the scope of the class of
which it is supposed to be the friend. This means that the function
which is declared as a friend should not be a member of the same
class.
• A friend function in C++ can be declared anywhere in the class, that
is, in the public section or the private section of the class.
• The friend function in C++ can be called (invoked) just like a normal
function using any instance of any class (object).
• A friend function in C++ cannot directly access the protected or
private data members of the class. It is required to use an object
(instance of that class) and then use the dot operator (.) to access
the data members.
• Friend functionality in C++ is not restricted to only one class. That
is, it can be a friend to many classes.
• Friend functions in C++ can use objects (instance of a class) as
arguments.
• A function can be declared as the friend of a class
in C++. This function is called a friend function for
that class.
• A friend function in C++ has the privilege to
access all the private and protected data of
members of the class whose friend it has been
declared.
• These functions can be used to access the
member functions of a class while still enforcing
data abstraction.
• Classes can also be declared as a friend of
another class.
Advantages/Disadvantages Of Friend Functions in C++
• The friend function in C++ has many advantages; let us look at some
of them.
• The friend function in C++ can provide a lot of degrees of freedom
in terms of options for interface design; that is, it allows us to use
different functions for other classes.
• A friend function in C++ can be used to access all the non-public
members(public access by default) of a class.
• The friend function in C++ increases the versatility of operator
overloading in C++ since functions can be overloaded as friend
functions as well.
• You can declare a member function of a class as a friend function of
another class allowing access to the data of the other class.
• Thefriend function in C++ can be used as a bridge between two
classes by having it operate on the instances of both classes.
• The friend function in C++ works symmetrically with all its friends,
that is, it will work the same way with all the classes.
Static Members
• Static data members are class members that are
declared using static keywords. A static member
has certain special characteristics. These are:
• Only one copy of that member is created for the
entire class and is shared by all the objects of that
class, no matter how many objects are created.
• It is initialized before any object of this class is
being created, even before main starts.
• It is visible only within the class, but its lifetime is
the entire program
• What is Friend Function in C++?
• We know that private class members are used for data hiding as they
cannot be accessed from anywhere outside the class. But what if you have
a global function that needs access to the private members of a certain
class to find the solution? As the function is of global scope, it cannot
access the private members.
• For example, suppose you have two classes: a Square class and a
Rectangle class. Both contain their length and width as private members.
You have a global function Area(), which takes in the length and width of a
rectangle or a square (length and width are the same) and returns the
area. Now, you want to calculate the area of the Square as well as the
rectangle. But, this method cannot access the private class members. One
option is to define the Area() method inside the two classes, so they can
access the private members, which will lead to repetitive code.
• Wouldn't it be helpful if, in some way, you could grant access to just this
function so that it can access the private members of the Square and
Rectangle classes in this case? This is exactly where the friend function in
C++ comes in.
• Formally, when a function is declared as the friend function for a class, it
can access all the private, public, and protected members of that class.
Since, by default, the public members of a class are accessible outside the
class, we mainly focus on the behavior of private and protected members.
• As friend function has many advantages, there are some
heavy disadvantages to it too, such as:
• The friendship in the friend function is not transitive or reciprocal or
inheritable; that is, we need to define every time that a function is a friend
function when inheriting a class from another class; that is, the
programmer needs to declare it as a friend function to every derived class
explicitly.
• Friend functions in C++ can not have a storage class specifier, meaning
they can not be declared static or extern in the code.
• Let us look at another concept similar to the friend function in C++ in the
next section.
Static Data Members in C++
• We can define class members’ static using the static
keyword in C++. When we declare a member of a class as
static it means no matter how many objects of the class are
created, there is only one copy of the static member
available throughout the program.

This is our class Test. This class is having two private


members that are a and b and it is having one public
constructor that is for initializing a and b. So, it is a simple
class that has two private members and a constructor for
initializing those private members. Then inside the main
function, we have created two objects of class Test as
follows:
• Here we have created two objects t1 and t2 for the class Test. When we have
created t1 then the constructor will be called t1 for and that will initialize a and b.
And same holds for t2. For a better understanding, please have a look at the below
image.

So, we have created two objects for the Test class. Then
every object will have it’s own a and b data members.
Now let us understand static data members. We are
defining a static variable in the above class as follows:
• So here inside the Test class, we have declared a static integer type
variable that is count. And also, we are incrementing its value by 1
in the constructor of the class Test. Here, the count is a static
variable. Then how does it works? When we are creating an object
t1 then how many members are there and for which memory will
be allocated? a, b and count. And when we are creating an object
t2, again a, b, and the count will be there. For a better
understanding, please have a look at the below image.
• As you can see in the above diagram, both t1 and t2 have separate
memory allocations for their a and b data members but the same
memory is shared for the count variable.
• So how many times this count variable is allocated? Only one time
the memory is allocated. And that memory is shared by both the
objects t1 and t2. Both of them will use the same count. So, it
means when we make a variable as static, that variable will occupy
memory only once. So static variables or static data members of a
class belong to a class. That doesn’t belong to an object. And all the
objects can share it. So, there will be only one copy and every
object will share that copy.
• Now let us see what happens. At the time of creating t1, the
constructor will assign a and b variables to 10 and 20 and
increment the count variable by 1. Assume the initial value of the
count is 0. So, after creating the object t1, the count will become 1
as shown in the below image.
• Then when we were creating t2,
the constructor was called that
assign t2’s a and b to 10 and 20
and increments the count. So,
previous the count value was 1,
then after incrementing, it will
become 2 as shown in the
below image.

So, both t1 and t2 have to access the same count variable. Such data members
are static data members of a class. Static members are belonging to a class and
they are common to all the objects. So static members are shareable members of
a class.
• When you have a static variable inside the class, you must have
declared it outside again. So, when we declare the class variable
outside the class, then it will become a global variable but we want
it to be accessible only inside the Test class. So, we can use the
scope resolution operator to make it accessible only inside the Test
class. The statement is,
• int Test::count = 0;
• This is an important statement. When you declared a static member
inside a class then that data member must be declared outside the
class again using the scope resolution operator.
• Now count is a global variable. A global variable is common for the
whole program. There is only one variable created for the entire
program. But we want the count variable to be used only within the
Test class. So, for this, we have given scope resolution to count. So,
two times we need the declaration of the count variable. It is just
like a global variable and you are making it accessible only to the
objects of the Test class. So that is the static variable. Only one-time
memory is allocated and all objects can access it. That’s all about
static data members.
• How to access Static Data Members in C++?
• Now let us see how to access that static variable.
cout << t1.count << endl;
• Can we access it like this? Yes, we can access it because it is
public inside the class. So, what will be displayed here? It
will display 2.
cout << t2.count << endl;
• Can we say this? Yes. So, what will be displayed here? Again
2 will be displayed. As count is public, so we can also write,
cout << Test::count << endl;
• Again 2 will be displayed. So here we have learned a new
thing. Static data members can be accessed using objects
or they can also be accessed using the class name if they
are public. You can directly access them using the class
name. So static member actually belongs to a class and
hence we can access them using the class name.
Output:

Note: When we define the data member of a class


using the static keyword, the data members are
called the static data member.
Static Member Functions in C++:
• Now we will discuss static member functions in C++. By declaring a member function as static in
C++, we make it independent of any particular object of the class. A static member function can be
called even if no objects of the class exist and the static functions are accessed using the class name
and the scope resolution operator (::) and even we can also access them using objects of the
class. Let us see. We are writing a static member function as follows: We have written this function
inside our Test class.
• This is a Static Member Function in C++ which is returning the value of the static count variable.
Now let us understand something. Inside getCount function, can we write a++? No, it’s not allowed.
But can we say count++ or return count? Yes, we can access count but you cannot access a or b. So,
the important thing is Static Member Functions in C++ can access only static data members of a
class. They cannot access non-static data members. So static member functions also belong to a
class. Let us see.

• cout << Test::getCount() <<endl;


• Can we call the getCount function? Yes, we can call it. We can call it by using the scope resolution
operator. This function will return the value of the count then that value will be printed on the
screen. So, what is the count initially? We did not create any object so the count is never
incremented. So, the value of the count is zero. Now if we write,
• Test t1;
cout << t1.getCount() << endl;
• Can we call this function getCount upon an object of class Test? Yes. It is just like static variables.
You can access static functions also by using the class name as well as using an object. Now let us
look at the program.
Key Points on Static Members in C++:
• Static data members are members of a class.
• Only one instance of static members is created for the
entire class and shared by all objects of that class, no
matter how many objects are created.
• It is initialized before any object of this class is created,
even before the main starts.
• They can be accessed directly using the class name.
• Static member functions are functions of a class, they can
be called using the class name, without creating the object
of a class.
• They can access only static data members of a class; they
cannot access non-static members of a class.
• It is visible only within the class, but its lifetime is the entire
program.
Constructor
• A constructor is a member function of a class that has the
same name as the class name. It helps to initialize the object
of a class.
• It can either accept the arguments or not. It is used to Syntax:
allocate the memory to an object of the class. It is called ClassName()
{ //Constructor's Body
whenever an instance of the class is created. }
• It can be defined manually with arguments or without
arguments.
• There can be many constructors in a class. It can be
overloaded but it can not be inherited or virtual.
• There is a concept of copy constructor which is used to
initialize an object from another object.
• Constructor is called by the compiler whenever the object of
the class is created, it allocates the memory to the object
and initializes class data members by default values or
values passed by the user while creating an object.
• Constructors don’t have any return type because their work
is to just create and initialize an object.
• Unique characteristics of Constructor:
• A Constructor is declared in the public section.
• The Constructor has no return type, not even void.
• The Constructor is called automatically when the class
object is created.
• The Constructor cannot be inherited, although the
derived class can call the base class constructor.
• Like other functions, constructors can have default
arguments.
• You cannot refer to the address of the Constructor.
• A Constructor cannot be virtual.
While defining a contructor you must
remeber that the name of
class A { constructor will be same as the name of
the class, and contructors will never
public: have a return type.
int x; Constructors can be defined either
inside the class definition or outside
// constructor class definition using class name and
A() scope resolution :: operator.

{
class A
// object initialization { public:
int i;
} }; A(); // constructor declared
};
// constructor definition
A::A()
{ i = 1;
}
Types of Constructors in C++
Constructors are of three types:
1. Default Constructor
2. Parametrized Constructor
3. Copy COnstructor
Default Constructors
• Default constructor is the constructor which doesn't take any argument. It has no parameter.
Syntax:
class_name(parameter1, parameter2, ...)
{ // constructor Definition }
For example: In this case, as soon as the object is created
class Cube
{ public:
the constructor is called which initializes
int side; its data members.
Cube() A default constructor is so important for
{ side = 10; initialization of object members, that even if
} we do not define a constructor explicitly, the
};
int main()
compiler will provide a default constructor
{ Cube c; implicitly.
cout << c.side;
}
OUTPUT:
10
class Cube OUTPUT:
{ 0 or any random value

public:
int side; In this case, default constructor provided by
}; the compiler will be called which will initialize
the object data members to default value, that
int main() will be 0 or any random integer value in this
{ Cube c; case.

cout << c.side;


}
Parameterized Constructors
• These are the constructors with
parameter. Using this
Constructor you can provide
different values to data
members of different objects, by
passing the appropriate values
as argument.
• By using parameterized
construcor in above case, we
have initialized 3 objects with
user defined values. We can
have any number of parameters
in a constructor. OUTPUT:
10
20
30
• Copy Constructor
• A Copy constructor is a type of constructor used to create a copy of an already
existing object of a class type. The compiler provides a default Copy Constructor to
all the classes. A copy constructor comes into the picture whenever there is a need
for an object with the same values for data members as an already existing object.
A copy constructor is invoked when an existing object is passed as a parameter.
• Syntax:
• //Copy constructor Employee :: Employee(Employee &ptr)
#include<iostream>
using namespace std;

class Employee {
private:
// Data members Employee1 using the parameterized constructor :
int salary, experience;
Salary: 34000
public:
// Parameterized constructor
Years of experience: 2
Employee(int x1, int y1) { Employee2 using copy constructor :
salary = x1;
experience = y1; Salary: 34000
}
Years of experience: 2
// Copy constructor
Employee(const Employee &new_employee) {
salary = new_employee.salary; Explanation:
experience = new_employee.experience; In this example, object employee1 of class Employee is declared in the
} first line of the main() function. The data
members salary and experience for object employee1 are assigned
void display() {
cout << "Salary: " << salary << endl; 34000 and 2, respectively, with the help of a parameterized
cout << "Years of experience: " << experience << endl; constructor, which is invoked automatically. When object employee2 is
} declared in the second line of the main() function, object employee1 is
}; assigned to employee2, which invokes the copy constructor as the
argument here is an object itself. As a result, the data member's salary
// main function
int main() { and experience of object employee2 are assigned to values possessed
// Parameterized constructor by the salary, and experience data members of object employee1 (i.e.,
Employee employee1(34000, 2); 34000, 2), respectively.
// Copy constructor
Employee employee2 = employee1;
cout << "Employee1 using parameterized constructor : \n";
employee1.display();
cout << "Employee2 using copy constructor : \n";
employee2.display();
return 0;
}
• What is a Destructor in C++?
• A Destructor is a member function that is instantaneously called whenever
an object is destroyed. The destructor is called automatically by the
compiler when the object goes out of scope, i.e., when a function ends,
the local objects created within it are also destroyed. The destructor has
the same name as the class name, but the name is preceded by a tilde(~).
A destructor has no return type and receives no parameters.
class scaler
{
public:
//constructor
scaler();
//destructor
~scaler();
};
• Characteristics of a Destructor in C++
• A destructor deallocates memory occupied by the object when it’s
deleted.
• A destructor cannot be overloaded. In function overloading,
functions are declared with the same name in the same scope,
except that each function has a different number of arguments and
different definitions. But in a class, there is always a single
destructor that does not accept any parameters. Hence, a
destructor cannot be overloaded.
• A destructor is always called in the reverse order of the constructor.
In C++, variables and objects are allocated on the Stack. The Stack
follows the LIFO (Last-In-First-Out) pattern. So, the deallocation of
memory and destruction is always carried out in the reverse order
of allocation and construction. This can be seen in the code below.
• A destructor can be written anywhere in the class definition. But to
bring an amount order to the code, a destructor is always defined
at the end of the class definition.
#include <iostream>
using namespace std;
class Department { OUTPUT:
public: Constructor Invoked for Department class
Department() {
// Constructor is defined. Constructor Invoked for Employee class
cout << "Constructor Invoked for Department class" << endl; Destructor Invoked for Employee class
}
Destructor Invoked for Department class
~Department() {
// Destructor is defined.
cout << "Destructor Invoked for Department class" << endl; Explanation:
} When an object named d1 is created in the first line
}; of main(), i.e. (Department d1), its constructor is
class Employee {
automatically invoked during the creation of the
public:
Employee() {
object. As a result, the first line of output,
// Constructor is defined. “Constructor Invoked for Department class,” is
cout << "Constructor Invoked for Employee class" << endl; printed. Similarly, when the e2 object of the
} Employee class is created in the second line
~Employee() {
of main(), i.e. (Employee e2), the constructor
// Destructor is defined.
cout << "Destructor Invoked for Employee class" << endl; corresponding to e2 is invoked automatically by the
} compiler, and “Constructor Invoked for Employee
}; class” is printed.
int main(void) { A destructor is always called in reverse order as that
// Creating an object of Department.
Department d1;
of a constructor. When the scope of the main function
// Creating an object of Employee. ends, the destructor corresponding to object e2 is
Employee e2; invoked first. This leads to printing “Destructor
return 0; Invoked for Employee class”. Lastly, the destructor
}
corresponding to object d1 is called, and “Destructor
Invoked for Department class” is printed.
• Constructors are an essential part of a class definition and
should be designed and built with care as these functions
define how new class objects are to be instantiated. They
allow us to create different instances of our classes.
• A constructor which does not receive any parameters is
called a Default Constructor or a Zero Argument
Constructor.
• A Parameterized Constructor is a constructor that can
accept one or more arguments.
• A Copy constructor is a type of constructor used to create a
copy of an already existing object of a class type.
• When the allocation of memory is done dynamically using a
dynamic memory allocator new in a constructor, it is known
as a Dynamic constructor.
• A Destructor deallocates memory occupied by the object
when it’s deleted.
Object Instantiation
Instantiation in C++
• Used to create an object (class instance) from a class.

Syntax
className objectName(parameters);

• Input requirements are taken from the constructor. A class can have multiple constructors with
different numbers of input parameters and types, to create different objects.
• An instance of a class is called an object.

• Example
using namespace std; //class looks like this
class Car
{
public: string make;
Car (string make)
{
this->make = make;
}
};
//instantiation, elsewhere in the program
Car myCar("Honda"); //passing in Honda into the make variable
• The this pointer in C++ points to the object that invokes the
member function. This keyword is only accessible within
the nonstatic member functions of a class/struct/union type.
• Same class variable and parameter names
• When the parameter name is the same as the private variable’s
name, we use the this keyword inside the method to distinguish
between the two when assigning values.
• class ClassName
{
private:
int sameName;
public:
ClassName functionName(int sameName)
{
this->sameName = sameName;
//the variable used with "this", is the class variable
}

You might also like