0% found this document useful (0 votes)
12 views233 pages

C++ Programming Language Overview

C++ is a middle-level programming language developed by Bjarne Stroustrup in 1979, combining features of both high-level and low-level languages. It supports object-oriented programming and has evolved through various versions, with the latest standard being C++23. C++ is widely used in applications such as operating systems, browsers, and game development due to its speed and efficiency.

Uploaded by

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

C++ Programming Language Overview

C++ is a middle-level programming language developed by Bjarne Stroustrup in 1979, combining features of both high-level and low-level languages. It supports object-oriented programming and has evolved through various versions, with the latest standard being C++23. C++ is widely used in applications such as operating systems, browsers, and game development due to its speed and efficiency.

Uploaded by

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

Introduction to C++

Designed By: VASUDHA


HISTORY OF C++
• According to IEEE C++ Language is the 4th most
popular language .
• The C++ programming language has a history going
back to 1979, when Bjarne Stroustrup (FATHER of
C++ ).
• He is currently working on the UNIX kernel for
distributed system for his Ph.D. thesis

Designed By: VASUDHA


Reason to develop C++….
• Stroustrup found that Simula65( 1979 popular lang.) had
features (Oop’s) that were very helpful for large software
development, but the language was too slow for practical use,
while BCPL was fast but too low-level to be suitable for large
software development.
• When Stroustrup started working in AT&T Bell Labs, he had
the problem of analyzing the UNIX kernel with respect
to distributed computing.
• Remembering his PhD experience, Stroustrup set out to
enhance the C language with Simula-like features.
• C was chosen because it was general-purpose, fast, portable
and widely used.

Designed By: VASUDHA


• In 1982 e builds a new language known as “C with Classes”
here C language is implemented along with the new concept
of OBJECT ORIENTED CONCEPT(Oop’s).
• Later in 1983 it is renamed as C++ where (++) symbol is a
(increment operator) which shows it is a INCRENENT in the
features of the basic C Language.
• In 1998 the C++ first official version known as (C++98) is
published in the market.
• C++ is standardized by the International Organization for
Standardization (ISO), with the latest standard version ratified
and published by ISO in October 2024 as ISO/IEC 14882:2024
(informally known as C++23).

Designed By: VASUDHA


BASICS OF C++
• C++ is middle level language.
• Compiler turbo c++.
• File extension (.cpp).
• Follow the concept of Oop's.
• Used for development of OS, System Drivers,
Browsers, Games etc.
• Ex : Adobe Photoshop, Amazon site.

Designed By: VASUDHA


Introduction to c++

Designed By: VASUDHA


Definition of c++
• C++ is a statically typed, compiled, general-purpose,
case-sensitive, free-form programming language that
supports procedural, object-oriented, and generic
programming.
• C++ is regarded as a middle-level language, as it
comprises a combination of both high-level and low-level
language features.
• C++ was developed by Bjarne Stroustrup starting in 1979
at Bell Labs in Murray Hill, New Jersey, as an
enhancement to the C language and originally named “C
with Classes” but later it was renamed “C++” .

Designed By: VASUDHA


Designed By: VASUDHA
Features of C++
1. SIMPLE:- C++ is one of the most-simple languages when it comes to
programming. It is also easy to understand and learn as it
originated from the C programming language.
2. Object Oriented Programming:- One of the most important features
because of which C++ got famous. Everything is treated as objects
in C++ that’s why it is called object-oriented programming. Objects
are used for performing all kinds of functionalities. It has
various features like Polymorphism and Inheritance.
3. PORTABILITY:- C++ is not platform independent but we can say it is
portable enough to run on different machines by adding some or no
changes at all.
4. Mid-Level Programming Language:- C++ programming language is a
collection of special features of low-level languages and high-level
languages.
5. Rich Library:- C++ library is full of in-built functions that save a huge
amount of time in the software development process.

Designed By: VASUDHA


6. Case Sensitive:- As C++ is originated from C, it is also purely
CASE sensitive that means lowercase and uppercase
characters written in code will have completely different
meaning and will be treated differently.
7. Compiler-Based:- Means Without compilation, you can’t
execute any C++ code.
8. Dynamic Memory Allocation:- Due to pointer support in the C++
language. Memory allocation can be easily done dynamically
rather than static.
9. Recursion:- Due to code reusability features, we can call any
function within a function saving memory space by not writing
the same code again and again. Code reusability is there for
every function.
10. Fast:- As compared to other programming languages. Execution
time and Compilation time of a code written in C++ language
are faster than any other programming language.

Designed By: VASUDHA


Uses/Applications of C++ Language
1. Operating Systems: Be it Microsoft Windows, APPLE(Mac OS-X),
Linux and SYMBIAN OS (One of the most widespread OS’s for
cellular phones) – all of them are programmed in C++.
2. Browsers: The rendering engines of various web browsers are
programmed in C++ simply because if the speed that it offers. Eg
MOZILLA FIREFOX
3. Libraries: Many high-level libraries use C++ as the core
programming language. For instance, several Machine Learning
libraries use C++ in the backend because of its speed. Tensorflow,
one of the most widely used Machine Learning .
4. Graphics: All graphics applications require fast rendering and just
like the case of web browsers, here also C++ helps in reducing the
latency. Eg Maya3D modelling and animation software.

Designed By: VASUDHA


5. Banking Applications: One of the most popularly used core-banking
system – Infosys uses C++ as one of the backend programming languages
and BLOOMBEG( SW provide real time financial information to investors)
6. Cloud/Distributed Systems: Large organizations that develop cloud
storage systems and other distributed systems also use C++ because it
connects very well with the hardware and is compatible with a lot of
machines.
7. Databases: MySQL – the most widely used databases are written in C++
and C.
8. Compilers: The compilers of various programming languages use C and
C++ as the backend programming language. This is because of the fact
that both C and C++ are relatively lower level languages and are closer to
the hardware and therefore are the ideal choice for such compilation
systems.

Designed By: VASUDHA


OBJECT ORIENTED
METHODOLOGY USING C++

Designed By: VASUDHA


Problem Decomposition or Problem
Solving:
What is Problem???
• A complex problem is one that, at first glance, we
don't know how to solve easily.

• Problem Decomposition It involves breaking down a


complex problem or system into smaller parts that are
more manageable and easier to understand.
• The smaller parts can then be examined and solved,
or designed individually, as they are simpler to work
with.

• It is of two type:
1. Top-Down Approach.
2. Bottom-Up Approach.
Designed By: VASUDHA
Designed By: VASUDHA
Designed By: VASUDHA
Top-Down Approach of Problem
Solving
Working approach:
• Breakdown the main problem into sub problems.
• Refining each sub problems into much smaller sub
problems.
• We Continue this process until every part is simple
enough to implement or solve.

Advantages of the Top-Down Design Model:


1. Simplifies Complex Problems
2. Easy to Identify Requirements
3. Promotes Reusability
4. Collaboration-Friendly(Promote team work)..
Designed By: VASUDHA
Bottom-Up Approach of Problem
Solving
Working approach:
• Identifying and specifying the smaller components (or
objects).
• Linking these smaller parts together to form larger
components.
• Continuously integrating them to complete the system.

Advantages of the Bottom-UP Design Model:

1. Reusability of Low-Level Components.


2. Focused Problem-Solving.
3. Increased Modularity.
Designed By: VASUDHA
Computer Language Evolution
• During the time of COMPUTER evolution there are
many different programming techniques are used,
1. Machine language (uses 0 and 1).
2. Assembly language (used in microprocessor).
3. Procedure Oriented language eg: COBOL, FORTRAN,
C language (used in compiler designing).
4. Object–Oriented Programming language eg: C++
language(partial), Java, c# etc...

Designed By: VASUDHA


Function Oriented Approach
or
Procedure-Oriented Programming(POP)
• Procedure: Sequence of things or statements.
• Procedure-oriented programming (POP) is a
programming paradigm where a program is structured
as a sequence of procedures (also known as functions,
subroutines, or routines).
• These procedures are essentially blocks of code designed
to perform specific tasks.
• It is a top-down approach.
Examples:
• C, Pascal, FORTRAN,

Designed By: VASUDHA


DRAWBACK of POP

1. It mainly concentrate on the development of functions and


less on data being used by functions.
2. No emphasis on DATA.
3. It also doesn’t model the REAL WORLD problems.
4. The FUNCTIONS are Action-Oriented and didn’t focus on the
real problem domain.
5. Most of functions share the GLOBAL DATA.
6. Data move openly around the system from function to
function.
7. Function transform data from one form to another.

Designed By: VASUDHA


Object oriented Approach(OOA)
• The object-oriented approach (OOA) is a
programming paradigm that structures a software
system around objects rather than functions or logic.
• Depending upon the features they support, they can
be classified into the following two categories:
1. Object-Based programming languages.
2. Object- Oriented programming languages.

Designed By: VASUDHA


Object-Based programming language
• Object-based programming languages are programming
languages that support the concept of objects but may not
include all the features of object-oriented programming
(OOP), such as inheritance and polymorphism.
• Examples : Visual Basic 6, and Fortran 90. JavaScript

Key characteristics of object-based languages:


•Objects: They allow the creation of objects, which encapsulate
data and behavior.
•Abstraction and Encapsulation: They often support abstraction
(hiding complex details) and encapsulation (bundling data and
methods).
•No or Limited Inheritance/Polymorphism.
Designed By: VASUDHA
Object-Oriented programming
languages
• These languages incorporates all the features
of object-based programming along with the
additional features i.e. inheritance,
polymorphism, and more complex class
hierarchies.
• Languages that support these features are
Java, C++, Python, and C# etc.

Designed By: VASUDHA


Object-Oriented Programming or
OOPs Concept’s
• Object oriented programming(Oop’s) aims to implement
real world entities like inheritance, hiding, polymorphism
etc. in programming.
• The main aim of OOP is to bind together the data and the
functions that operates on them so that no other part of
code can access this data except that function.
• The basic characteristics of an Object-Oriented Programming
language is:
1. Object
2. Classes
3. Data abstraction and encapsulation
4. Inheritance
5. Polymorphism
Designed By: VASUDHA
Features of Oop’s
• Emphasis on data rather than procedure.
• Data structure are designed in such a way that they
characterize the object.
• Function that operate on the data of an object are tied
together in the data structure.
• Data is hidden and cannot be accessed by external function.
• Object’s may communicate with each other through
functions.
• Follow the bottom-up approach.

Designed By: VASUDHA


Understanding “Object and Class”

Designed By: VASUDHA


.

OBJECTS
• In C++, Object is a real-world entity, for example, chair, car,
pen, mobile, laptop etc.
• In other words, object is an entity that has state and behavior.
Here, state means data and behavior means functionality.
• Object is a runtime entity it is created at runtime.
• Object is an instance of a class. When a class is defined, no
memory is allocated but when it is instantiated (i.e. an object
is created) memory is allocated .
• All the data members and member function defined in the
class can be accessed through object using dot (.) operator.
• Before create an objects and use them in C++, we first need
to create a classes.

Designed By: VASUDHA


OBJECT(Identity, State and Behavior)
1. Identity: Identity is the property that
uniquely distinguishes one object from
all other objects, even if they have
identical states and behaviors.

2. State: The state of an object is


defined by its attributes (or properties
or data fields) and the current values
these attributes hold.

3. Behavior: The behavior of an object


refers to the actions it can perform and
how it responds to external stimuli.

Designed By: VASUDHA


CLASSES
• A class is a user-defined data type, which holds its own data
members and member functions that can be accessed and used by
creating an instance of that class i.e. (OBJECT).

 Data Members: These are the variables(attributes) that are defined


inside the class.
 Member Functions: Functions declared inside a class. Also referred
to as a member method.

• Encapsulation: A class binds data and the functions that


manipulate that data into a single unit called class.

• Class is the Blueprint for objects: it defines the structure


and behavior that objects of that class.

• Class is defined using the keyword class .


Designed By: VASUDHA
• Access Specifiers:
• Classes use access specifiers (public, private, protected) to
control the visibility and accessibility of their members from
outside the class.
 PUBLIC: Members are accessible from anywhere.
 PRIVATE: Members are accessible only within the class itself.
 PROTECTED: Members are accessible within the class and by
derived classes

Designed By: VASUDHA


CLASS DIAGRAM

Designed By: VASUDHA


Designed By: VASUDHA
ENCAPSULATION
• It is the wrapping up of data and functions into a
single unit (called CLASS).
• The data is not accessible to the outside world, and
only the functions of that class can access it.
• “This insulation of data from the outside world to
prevent unauthorized access is known as DATA
HIDING” .

Designed By: VASUDHA


Designed By: VASUDHA
ABSTRACTION
• It is the process of representing essential features
without including the background details or
explanations.
• Abstraction is implemented to reduce complexity
of code.
• In C++ the abstraction is implemented using
CLASSES.
• Abstraction is also implemented using Access
Specifiers( PUBLIC and PRIVATE).
• Those classes which uses the concept of data
abstraction, are known as ABSTRACT DATA TYPE(
ADT).
Designed By: VASUDHA
Types of Abstraction:
1. Data abstraction - This type only shows the required
information about the data and ignores unnecessary details.
2. Control Abstraction - This type only shows the required
information about the implementation(working) and ignores
unnecessary details.

Designed By: VASUDHA


INHERITANCE
• Inheritance is a mechanism in which the object of one class
acquires the property of object of another class.
• The parent class is known as BASE CLASS and the child class
is known as DERIVE CLASS.
• In inheritance, a child inherits the traits of his/her parents.
• With inheritance, we can reuse the data and methods of the
existing class. Hence, inheritance facilitates Reusability and is
an important concept of OOPs.

Designed By: VASUDHA


TYPE OF INHERITANCE
• There are Various types of inheritance:
1. Single Inheritance: In this there is only one derive class which inherit the
features from single base class.

2. Multiple Inheritance: In this there is only one derive class which inherit the
features from more than one base class.

3. Multilevel Inheritance: In Multilevel Inheritance, one derive class can inherit


from another derived class. Hence, the derived class becomes the base class
for the new derive class.

4. Hierarchical Inheritance: In Hierarchical Inheritance, one base class is


inherited by many derive classes.

5. Hybrid Inheritance: Hybrid inheritance is a combination of Single and


Multiple inheritance.
Designed By: VASUDHA
Single Inheritance Multiple Inheritance Multilevel Inheritance

Hierarchical Inheritance Hybrid Inheritance

Designed By: VASUDHA


POLYMORPHISM
• The word polymorphism means poly means MANY and
morph means FORM i.e. One name and many forms.

• In simple words, we define polymorphism as the ability


of an entity to behave different in different scenarios.

• For example, A person at the same time can have


different characteristics. Like a man at the same time is a
father, a husband, an employee. So, the same person
posse's different behavior in different situations.

In C++ polymorphism is of two types:


 Compile time Polymorphism
 Runtime Polymorphism
Designed By: VASUDHA
1. Compile time polymorphism: This type of polymorphism is
achieved by function overloading or operator overloading.

 Function Overloading: When there are multiple functions with


same name but different parameters then these functions are
said to be overloaded. Functions can be overloaded by change in
number of arguments or/and change in type of arguments.
 Example:
void sum(int x, int b)
void sum(float x, float y)
void sum(int x, int y, int z)

 Operator Overloading: C++ also provide option to overload


operators.
 For example: we can make the operator (‘+’) for string class to
concatenate two strings. We know that this is the addition
operator whose task is to add to operands.
Designed By: VASUDHA
2. Runtime polymorphism: This type of
polymorphism is achieved at run time by using
Function Overriding (Virtual function).

 Function overriding:
• Function overriding is only possible within an
inheritance, where the function of the derived
class override the function of the base class.
• Both the functions have same name, return type,
and parameters list. The decision of which
version of the function (base or derived) to
execute is made at runtime.
Designed By: VASUDHA
Advantages and Disadvantages of Object Oriented
Programming Language

ADVANTAGES:
• High Performance and Efficient memory
management.
• Support Object-Oriented Programming (OOP)
concepts.
• Highly portable language.
• Provides direct memory access through pointers.
• Support different libraries, frameworks, and tools
that can accelerate development and simplify
complex tasks.

Designed By: VASUDHA


DISADVANTAGES:
• Manual Memory Management using pointers
can be a source of errors like memory leaks.
• Lack of Built-in Garbage Collection requiring
manual memory deallocation.
• Security Concerns: The use of pointers and
direct memory access can introduce security
vulnerabilities if not implemented with
caution.

Designed By: VASUDHA


Difference Between C AND C++
SEQ Basis of C C++
.NO difference
1 Programming It is a Procedural It is an Object-Oriented
type Oriented language. Programming language.
2 Approach Top Down programming C++ follow bottom-up
approach programming approach.
3 File extension The file extension of a C The file extension of a c+ +
program is ( .c) program language is(.cpp)
4 Program division In C programming In C++ programming language,
language, a big program a big program code is divided
code is divided into into Objects and Classes.
small pieces which is
called functions.
5 Standard I/O In C (scanf) and (printf) In C++ (cin») and (cout«) are
operations are used for the given for standard input and
standard input and output operations.
output
Designed By: VASUDHA
Structure of C++ programs and its
Operators

Designed By: VASUDHA


Basic Structure of A Complete C++ Program
1. Documentation Section
• comments.(// or /*………..*/)
2. Preprocessor Directives

3. Global Declaration Section

4. Class declaration or definition


• Data members declare.
• Member function declare and define.

5. Main Function declaration.


• Object declaration part.
• Accessing member functions (using dot operator).

Designed By: VASUDHA


[Link] Section
• In Documentation section we give the Heading and Comments.
• Comment statement is the non-executable statement. Comment
can be given in two ways:

1. Single Line Comment: Comment can be given in single line by


using "II".
• Example: // Text Line …………

2. Multiple Line Comment: Comment can be given in multiple lines


starting by using "/*" and end with "*/".

• Example: /* Text Line ………… */

Designed By: VASUDHA


[Link] Directives
Pre-compiler statements are divided into two parts.
1. Link Section: In the Link Section, we can link the compiler function like
cout<<, cin>>, sqrt ( ), clrscr ( )etc. with the INCLUDE subdirectory
having header files like iostream.h, conio.h, math.h etc. It becomes very
useful during the compilation and the linkage phase.

• The general syntax is: #include <header file> .or #include "header file"
For example: #include <iostream.h>, #include <conio.h> , #include "dos.h“

2. Definition Section: The second section is the Definition section by using


which we can define a variable with its value. For this purpose, define
statement is used.
• The general syntax is: #define variable name value
For example:
• #define PI 3.142
• #define A 100
• #define NAME "Dinesh"

Designed By: VASUDHA


[Link] Declaration Section

• In this section, we declare some variables before starting of the main


program or outside the main program. These variables are globally
declared and used by the main function or sub function. These variables
are called global variables.
• int a, b, c;
• float x,y,z;
• char ch, name[10], address[20];

Designed By: VASUDHA


[Link] Declaration or Definition
1. Class name or name of class
• It is mainly the name given to a particular class. It serves as a name
specifier for the class, using which we can create objects.
• The class is specified by keyword "class".
• example: class Circle (Here Circle is the class name).

2. Data Members
• These are the data-type properties that describe the characteristics of a
class.
• We can declare any number of data members of any type in a class.
• We can say that the variables in C and data members in C++.
• example: float area; int a=10

3. Member Functions
• These are the various operations that can be performed to data members
of that class.
• Member functions are access using object and dot operator.
• example: void read(), void display()
Designed By: VASUDHA
4. Access Specifier
• Access Specifier are used to identify access rights for the data
members and member functions of the class. Depending upon the
access level of a class member, access to it is allowed or denied.
• There are three main types of access Specifier in C++ programming
language:
 [Link]: A private member within a class denotes that only
members of the same class have accessibility. The private member
is not accessible from outside the class.
 2. Public: Public members are accessible from outside the class.
 [Link]: A protected access specifier is a stage between private
and public access. If member functions defined in a class are
protected, they cannot be accessed from outside the class but can
be accessed from the derived class (inheritance).

Designed By: VASUDHA


5. Main Function()
1. Object declaration part
• We can declare objects of class inside the main program or outside the main
program.
• Defining objects of class data type is known as class instantiation (instances of
class).
• example:

Circle c1; //Object created outside main

main( )
{Circle c2; //Object created inside main
}

2. Accessing member functions (using dot operator)


• The member function define in the class are access by using dot (.) operator.
• Obj1. member function();
• example: [Link]();

Designed By: VASUDHA


II Program to display data.. //Documentation Section: Use single line comment
#include <iostream.h> // Preprocessor Directives: Link and Definition Section
#include <conio.h>
int n1; //Global Variable

Class Display //Class definition (Circle class is created)


{ Private: //Access specifier
Int n2; // Local Variable

Public: //Access specifier


void getdata( ) //Member functions 1
{ cout<<“enter first no.”;
cin>>n1;
cout<<“enter second no.”;
cin>>n2;
}
Void showdata( ) //Member functions 2
{ cout<< “\n”<< “first no =“<< n1;
cout<< “\n”<< “second no =“<< n2;

}
};
main ( ) // Main program
{
clrscr();
Display d1; // Object of the class is created
[Link]( ); //Member functions is accessed through object.
[Link]( );
getch( );
Designed By: VASUDHA
}
OPERATORS IN C++

Designed By: VASUDHA


Operators In C++
• Operators in C++ are a set of symbols that
enable users to manipulate values in the
program and operate a variety of operations
on them.

Designed By: VASUDHA


Scope resolution operator in C++
• The scope resolution operator is denoted by :: (two
colons).
• It is a fundamental operator used to resolve ambiguities
when referring to identifiers (variables, functions, types,
or constants) that might exist in different scope.
• In C++, scope resolution operator is (::) It is used for following
purposes.

1. To access a global variable when there is a local variable


with same name.
2. Accessing members of a class from outside the class
definition.
3. Accessing static members of a class.
4. Accessing members within a namespace
Designed By: VASUDHA
1. To access a global variable when there is a local variable
with same name:
When a local variable has the same name as a global
variable, the local variable takes precedence within its
scope.

#include<iostream.h>
int x=30; // Global x

int main()
{
int x = 10; // Local x
cout << "Value of global x is " << ::x; //output 30
cout << "\nValue of local x is " << x; //output 10
return 0;
} Designed By: VASUDHA
2) To define a function outside a class.(Accessing members of
a class from outside the class definition )

• When defining member functions outside the class declaration, the


scope resolution operator is used to specify which class the function
belongs to
#include<iostream>
class A
{
public:
void fun(); // Only declaration
};

void A::fun() // Definition outside class using ::


{
cout << "fun() called";
}
int main()
{ A a;
[Link]();
return 0;
} Designed By: VASUDHA
3) Accessing static members of a class:
Static members (variables or functions) belong to the
class itself, not to individual objects. They are
accessed using the class name and the scope
resolution operator.

Class num
{ public:
static int var1;
};
int num::var1 = 5; // Definition of static member
int main()
{
cout << num::var1 << endl; // Accessing static member
return 0;
}
Designed By: VASUDHA
4) Accessing members within a namespace:
• Namespaces are used to organize code and prevent
naming conflicts. The scope resolution operator is
used to access identifiers within a specific namespace.

#include<iostream.h>
#include<conio.h>
Using namespace std;

Int main()
{ std::cout<<“hello world”;
getch();
}

Designed By: VASUDHA


Dynamic Memory allocation in C++
(New, Delete Operator)
• Dynamic memory allocation refers to the manual
management of memory during program execution, allowing
for flexible memory usage based on runtime needs.
• C uses malloc() and calloc() function to allocate memory
dynamically at run time and uses free() function to free
dynamically allocated memory.
• C++ supports these functions and also has two
operators new and delete that perform the task of allocating
and deallocating the memory in a better and easier way.
• In dynamic memory allocation Heap memory is allocated at run time.

Designed By: VASUDHA


new operator
• The new operator denotes a request for memory allocation on the Heap.
• If sufficient memory is available, new operator initializes the memory and
returns the address of the newly allocated and initialized memory to the
pointer variable.
Syntax:
Pointer_variable = new data_type;
Here,
• Pointer-variable is the pointer of type data-type.
• Data-type could be any built-in data type including array or any user
defined data types including structure and class.
• Eg: int *p = NULL;
p = new int;
(or)
int *p = new int;

Designed By: VASUDHA


1. Initialize memory: We can also initialize the memory using new operator:
• Example: int *p = new int(25);
float *q = new float(75.25);

2. Allocate block of memory: new operator is also used to allocate a


block(an array) of memory of type data-type.
• Example: int *p = new int[10];
• Dynamically allocates memory for 10 integers continuously of type int and
returns pointer to the first element of the sequence, which is assigned to
p(a pointer). p[0] refers to first element, p[1] refers to second element and
so on.

Designed By: VASUDHA


Delete Operator
• Since it is programmer’s responsibility to deallocate dynamically allocated
memory, programmers are provided delete operator by C++ language .
Syntax:
• delete pointer-variable;

Examples:
• delete p;
• delete q;

Designed By: VASUDHA


#include<iostream.h>
Int main()
{ int*p; // declaring int and float pointer
float*pf;

p= new int; //dynamic memory allocation


pf=new float;

*p= 40; //assigning value to the memory


*pf=50.00f;
cout<<*p<<endl; //printing the value
cout<<*pf<<endl;

delete p; // deallocate the memory


delete pf;
return 0;
}

Designed By: VASUDHA


(Cin>>) and (cout<<) operators
• C++ comes with libraries which provides us with many ways
for performing input and output.
• In C++ input and output is performed in the form of a
sequence of bytes or more commonly known as streams.
1. Input Stream: If the direction of flow of bytes is from the
device(for example, Keyboard) to the main memory then
this process is called input.
2. Output Stream: If the direction of flow of bytes is opposite,
i.e. from main memory to device( display screen ) then this
process is called output.
• iostream: iostream stands for standard input-output
stream. This header file contains definitions to objects
like cin, cout etc.

Designed By: VASUDHA


Standard output stream (cout):
• The C++ cout statement is the instance of the ostream class.
• It is used to produce output on the standard output device
which is usually the display screen.
• The data needed to be displayed on the screen is inserted in
the standard output stream (cout) using the insertion
operator(<<).
• Eg. Cout<<“hello”;

Designed By: VASUDHA


standard input stream (cin):
• In C++ cin statement is the instance of the
class istream (input stream class) and is used to
read input from the standard input device which is
usually a keyboard.
• The extraction operator(>>) is used along with the
object cin for reading inputs.
• The extraction operator extracts the data from the
object cin which is entered using the keyboard.
• Eg, cin>>a;

Designed By: VASUDHA


CLASS AND OBJECT

UNIT 2

Designed by:Vasudha
Information Hiding(Data hiding)
• Information hiding is one of the most important principles of OOP
inspired from real life which says that all information should not
be accessible to all persons. Private information should only be
accessible to its owner.

• “Showing only those details to the outside world which are


necessary for the outside world and hiding all other details from
the outside world.”
• In the perspective of Object Oriented Programming Information
Hiding is,
• “Hiding the object details (state and behavior) from the users”
• Which mainly includes:-
 Encapsulation
 Abstraction
 Data Hiding
Designed by:Vasudha
Abstract Data Types
• ADT is the model of data type which holds:
 Properties of the data.
 Operations that can be performed on the data.

• It is a conceptual model that defines a set of operations and


behaviors for a data structure, without specifying how these
operations are implemented or how data is organized in memory.
• It only defines what operations are to be performed but
not how these operations will be implemented.
• It is called "abstract" because it provides an implementation-
independent view.
• abstract data type are list, stack, queue etc.

Designed by:Vasudha
Designed by:Vasudha
Common examples of ADTs include:
•List: A sequence of elements with operations like insert, delete, access,
and search
•Stack: A LIFO (Last-In, First-Out) structure with operations like
•push (add an element).
•pop (remove the most recent element).
•Queue: A FIFO (First-In, First-Out) structure with operations like
•enqueue (add an element to the rear).
•dequeue (remove an element from the front).
•peek (retrieves the element at the front (or head) of the queue without
removing it). Designed by:Vasudha
Functions in C++
• A function is a set of statements that take inputs, do some
specific computation and produces output.
• Depending on whether a function is predefined or created by
programmer; there are two types of function:
1. Library Function
2. User-defined Function

Designed by:Vasudha
Library Function
• Library functions are the built-in function in C++
programming.
• Programmer can use library function by invoking function
directly; they don't need to write it themselves.
• Example: sqrt(), main(), getch() etc.
User-defined Function
• A user-defined function groups code to perform a specific task
and that group of code is given a name(identifier).
• When the function is invoked from any part of program, it all
executes the codes defined in the body of function.

Designed by:Vasudha
Designed by:Vasudha
Functions with parameters
• A parameter is a list of variables that is used to pass
information into the function and send information out of
function back to the calling program.
• Parameter is also known as argument.
• There are mainly two modes of parameter passing is given:
1. Actual Parameters
2. Formal Parameters

Designed by:Vasudha
Actual Parameters :
• The arguments that are passed in a function call are called
actual arguments.
• There is no need to specify datatype in actual parameter.
• Eg: add(num1,num2);
Formal Parameters :
• These are the variables which receives the value from the
function called.
• The datatype of the receiving value must be defined.
• The scope of formal arguments is local to the function definition
in which they are used.
• Eg: int add(int a, int b)
{…….
}
Designed by:Vasudha
Designed by:Vasudha
Passing Parameters to a function by VALUE or by
REFERENCE Method:

1. Call by Value (Pass by value):


• In this method of passing arguments to a function, copies the
actual value of an argument into the formal parameter of the
function.
• Any modifications to the formal parameter variable inside the
called function or method affect only the separate storage location
and will not be reflected in the actual parameter in the calling
environment.

Designed by:Vasudha
#include <iostream.h> Call by Value
#include <conio.h>

class Swap
{ public:
void SwapByValue(int num1, int num2)
{ int temp = num1;
num1 = num2;
num2 = temp;
cout << ‘Swapped value:”<<num1<<num2 << endl;
}
};

int main()
{ Swap s;
int a = 5, b = 10;
cout << "Before swapping: a = " << a << ", b = " << b << endl;
s. SwapByValue(a, b);
cout << "After swapping: a = " << a << ", b = " << b << endl;
getch();
return 0;
}
Designed by:Vasudha
2. Call by reference(Pass by reference)
• In this method of passing arguments to a
function copies the reference of an actual
argument into the formal parameter.
• Any changes to the formal parameter are
reflected in the actual parameter in the
calling environment as formal parameter
receives a reference (or pointer) to the
actual data.
• This method is efficient in both time and
space.
Designed by:Vasudha
Call by Reference
#include <iostream.h>
#include <conio.h>

class Swap
{ public:
void swapByReference(int &num1, int &num2)
{ int temp = num1;
num1 = num2;
num2 = temp;
cout << ‘Swapped value:”<<num1<<num2 << endl;
}
};

int main()
{ Swap s;
int a = 5, b = 10;
cout << "Before swapping: a = " << a << ", b = " << b << endl;
[Link](a, b);
cout << "After swapping: a = " << a << ", b = " << b << endl;
getch();
return 0;
} Designed by:Vasudha
INLINE FUNCTION
• In inline function the compiler is advised to insert the function's
body directly into each place where the function is called, rather
than performing a traditional function call. It is also known as
inlining.
• Aims to reduce the overhead associated with function calls like
pushing arguments onto the stack, jumping to the function's address,
and returning is eliminated.
• The inline keyword is a suggestion to the compiler, not a
command. The compiler may choose to ignore the inline keyword for
large or complex functions, or functions with loops or recursion.
• This substitution is performed by the C++ compiler at compile time.
• Inline function may increase efficiency if the Code is small.

• SYNTEX:
inline return-type function-name(parameters)
{
// function code;
}
Designed by:Vasudha
Designed by:Vasudha
#include <iostream.h>
inline int cube(int c)
{
return c*c*c;
}

int main()
{ int value, n;
Cout<<“enter the number”;
Cin>>n;
Value= cube(n);
cout << "The cube of n=“<<value<<endl;
return 0;
} Designed by:Vasudha
Friend Functions

• A friend function of a class is defined outside that class scope but it has
the right to access all private and protected members of the class.
• Even though the prototypes for friend functions appear in the class
definition, friends are not member functions.
• To declare a function as a friend of a class, precede the function
prototype in the class definition with keyword friend.
• A friend function can be given special grant to access private and
protected members of that class.
• A friend function can be:
a) A global function
b)A method of another class

Designed by:Vasudha
Designed by:Vasudha
Declaration of friend function in C++:
class class_name
{ ... .. ... friend return type function name(class object); ... .. ...
}

Designed by:Vasudha
Friend Function Characteristics
• The friend function is not in class scope.
• It should be declared inside the class with ‘friend’ keyword.
• It is not in class scope. So, it cannot be called by objects of the
class.
• It can be called like a normal function.
• Usually, it has class objects as arguments.
• It cannot access member variables or functions directly, but
can only be accessed by the help of the objects of the class.
• It can be declared with any access specifier and the access
specifier does not have any impact on the friend function.
• Friendship can't be inherited.

Designed by:Vasudha
1. Global Function as Friend Function
#include <iostream.h>
class Box
{ double width;
public:
void setWidth( )
{ cout<<“enter the value of width”;
cin>>width;
}
friend void print( Box ); // Friend function is Defined.
};

void print( Box b) // Global function definition


{
cout << "Width of box : " << [Link] <<endl;
}
int main()
{ Box b;
[Link]();
print( b); // friend function called
return (0);
}
Designed by:Vasudha
2. Member Function of Another Class as Friend Function

#include <iostream>
//CLASS 1 IS CREATED /CLASS 2 IS CREATED
class base class print
{ public: int p1,p2; {
public: public:
void setvalue() void print_function(base b)
{ p1=10; {
p2=99; cout << "Variable1 value: "<< b.p1<< endl;
} cout << "Variable2 value: "<< b.p2;
friend void print_function(base); }
};
};
int main()
{
base b1;
print p3;
[Link]();
p3.print_function(b1);

return 0;
}
Designed by:Vasudha
• Friend Class Example:
#include <iostream.h>
//CLASS 1 IS CREATED
//CLASS 2 IS CREATED
class Data
class print
{
{
int i =3;
public:
friend class print;
void display(data d)
};
{cout<<"The value of i is : "<<d.i;
}
int main()
};
{
Data d;
print p;
[Link](d);
return 0;
}
Designed by:Vasudha
OBJECT
• Object is a real world entity.
• An object has state, behavior, and identity; the structure and
behavior of similar objects are defined in their common class.”

Designed by:Vasudha
1. Passing Object as an argument in
C++ function
• In any programming language we can pass any
type of arguments within the member function
and there are any numbers of arguments.

• In C++ programming language, we can also pass


an object as an argument within the member
function of class.

Syntax:
function_name(object_name);

Designed by:Vasudha
// WAP which take values from the objects and perform the sum and display it.
# include<iostream.h>
class Demo
{ private: int a;
public:
void set(int x)
{ a = x;
}
void sum(Demo d1, Demo d2)
{ a = d1.a + d2.a;
}
void print()
{ cout<<"Value of a : "<< a <<endl;
}
};
int main()
{ Demo d1,d2, d3;
[Link](10); //Message Passing
[Link](20); //Message Passing
[Link](d1,d2); //passing object d1 and d2
[Link]();
[Link]();
[Link]();
return 0;
} Designed by:Vasudha
Output
• Value of A : 10
• Value of A : 20
• Value of A : 30

Designed by:Vasudha
#include <iostream.h>
class Total
{
public: int a;
public: void add(Total E)
{ a = a + E.a;
}
};
int main()
{
Total E1, E2;
E1.a = 50; // Values are initialized for both objects
E2.a = 100;
cout << "Initial Values \n";
cout << "Value of object 1: " << E1.a << "\n& object 2: " << E2.a << "\n\n";
[Link](E1); // Passing object as an argument to function add()
cout << "New values \n";
cout << "Value of object 1: " << E1.a << "\n& object 2: " << E2.a << "\n\n";
return 0; }
Designed by:Vasudha
• Output:
Initial Values Value of
object 1: 50 & object 2: 100
New values Value of
object 1: 50 & object 2: 150

Designed by:Vasudha
2. Array of Objects in C++

• An object of class represents a single record in memory, if


we want more than one record of class type, we have to
create an array of class type or object.
• As an array is a collection of similar type, therefore an
Object array can be a collection of class type.

SYNTEX:
• ClassName ObjectName[Number of Objects];

Designed by:Vasudha
Designed by:Vasudha
class employee
{public: int id;
char name[25];
int age;
long salary;
public:
void getdata()
{ cout<<"Enter Employee Id : ";
cin>>id;
cout<<"Enter Employee Name : ";
cin>>name;
cout<<"Enter Employee Age : ";
cin>>age;
cout<<"Enter Employee Salary : ";
cin>>salary;
}
void putdata()
{ cout<<“ID of employee”<<id<<endl;
cout<<“Name of employee”<<name<<endl;
cout<<“Age of employee”<<age<<endl;
cout<<“Salary of employee”<<salary<<endl;

}
};
Designed by:Vasudha
void main()
{
employee e1,e2,e3;
[Link](); //first employee data inserted.
[Link](); //first employee data printed.
[Link](); //second employee data inserted.
[Link](); //second employee data printed.
[Link](); //third employee data inserted.
[Link](); //third employee data printed.
getch();
}

Designed by:Vasudha
void main()
{ int i;
employee e[3]; //Creating Array of 3 Employees
for(i=0;i<3;i++)
{ cout<<"\n Enter the details of Employee";
e[i].getdata();
}
cout<<"\nDetails of Employees are";
for(i=0;i<3;i++)
{ e[i].putdata();
}
}

Designed by:Vasudha
Constructors in C++
What is constructor?
• A constructor is a special member function of the class that is
automatically called when an object of a class is created.

How constructors are different from a normal member function?

• Same Name as Class: Constructor has same name as the class itself.
• No Return Type: Constructors do not have a return type, not even
(void).
• Automatic Invocation: They are called implicitly by the compiler when
an object is instantiated, unlike regular member functions that require
explicit called.
• Different Type: A constructor can be created with parameter or without .
• If we do not specify a constructor, C++ compiler generates a default
constructor for us (expects no parameters and has an empty body).
Designed by:Vasudha
Designed by:Vasudha
Types of Constructors
1. Default Constructors:
• Default constructor is the constructor which doesn’t take any
argument means It has no parameters.
• Default constructor called automatically when the object is
created .
• Note: Even if we do not define any constructor explicitly, the
compiler will automatically provide a default constructor
implicitly.

Designed by:Vasudha
#include <iostream>
class data
{
public:
data() // Default Constructor created
{ cout<<“default constructor is called”;
}
void display()
{ cout<<“member function of class”;
}
};
int main()
{ data d;
[Link]();
return (0);
}

Designed by:Vasudha
#include <iostream>
class number
{
public:
int a, b;
number() // Default Constructor
{
a = 10;
b = 20;
}
};
int main()
{
number c;
cout << "a: " << c.a << endl << "b: " << c.b;
return 0;
}

Designed by:Vasudha
2. Parameterized Constructors:
• Constructors that receive arguments/ parameters is called as
parameterized constructors.
• These parameterized constructors are called when the object of the
class is created.
• The parameters are passed to the constructor with the object its self.
 Uses of Parameterized constructor:
– It is used to initialize the different objects with different values
when they are created.
 Can we have more than one constructors in a class?
Yes, It is called Constructor Overloading.

Syntex:
class Name(parameter list)
{
}
Designed by:Vasudha
#include<iostream>
class data
{ public: int a;

data() //default constructor called


{cout<<“default constructor is called”<<endl;
}

data(int x) // parameterized constructor called


{ cout<<"Parameterized Constructor is called"<<endl;
a = x;
}
void print() // Normal Member function called
{ cout<<"The value of a is"<<a<<endl;
}
};
int main()
{ data r1(8); //Passing value to Parameterized Constructor
[Link]();
return 0;
}

Designed by:Vasudha
// C++ program to calculate the area of a wall
#include <iostream>
class Wall
{
double length;
double height;
public:
Wall(double len, double hgt) // create parameterized constructor
{ length = len;
height = hgt;
}
double Area()
{ return length * height;
}
}; Designed by:Vasudha
int main()
{
Wall wall1(10.5, 8.6);
Wall wall2(8.5, 6.3);
cout << "Area of Wall 1: " << [Link]() << endl;
cout << "Area of Wall 2: " << [Link]() << endl;
return 0;
}

Designed by:Vasudha
.

3. Copy Constructor:
• A copy constructor is a member function that
initializes an object using another object of the
same class.
• Copy constructor takes a reference to an object
of the same class as an argument.

Syntax : ClassName (const Class_Name &old_obj);


const Class_Name& obj:
A constant reference to an object of the same class.
• Using a const reference ensures that the original object is not
modified during the copy process, and using a reference avoids
unnecessary copying of theDesigned
object itself
by:Vasudha
class A
{
A(const A &x) // copy constructor.
{
…………
}
}

copy constructor can be called in the following ways:

Designed by:Vasudha
Purpose of a Copy Constructor
• a copy constructor is to ensure a proper and independent copy of
an object, especially when the object contains dynamically
allocated memory or other resources.

Shallow Copy vs. Deep Copy:

• Shallow Copy: The default copy constructor provided by the


compiler.
• a shallow copy will only copy the pointer addresses, leading to
both objects pointing to the same memory location.

• Deep Copy: A user-defined copy constructor is necessary to


perform a deep copy.
• In deep copy a new memory is allocated for the copied object's
data members, and the contents of the original object's are copied
to the new memory location.
Designed by:Vasudha
#include <iostream.h>
class show
{
public: int x;
show( int a) // parameterized constructor.
{ x=a;
}
show(const show &a1) // copy constructor
{ x = a1.x;
}
};
int main()
{
show a1(20); // Calling the parameterized constructor.
show a2(a1); // Calling the copy constructor.
cout<<a2.x;
return 0;
}

Designed by:Vasudha
#include<iostream.h> int main()
class Point {
{ private: int x, y; Point p1(10,15);
public: Point p2=p1; // Copy constructor
Point(int x1, int y1) is called here
{ x = x1; p1.print_value();
y = y1; p2.print_value();
} return 0;
Point(const Point &p1) // Copy }
constructor
{ x = p1.x;
y = p1.y;
}
void print_value()
{ cout<<"\nvalue of x="<<x;
cout<<"\nvalue of y="<<y;
}
}; Designed by:Vasudha
Destructors in C++
• What is destructor?
Destructor is a member function which destructs or deletes an object.

• When is destructor called?


A destructor function is called automatically when the object goes out of
scope:
(1) the function ends
(2) the program ends
(3) a block containing local variables ends
(4) a delete operator is called

 How destructors are different from a normal member function?


Destructors have same name as the class preceded by a tilde (~)
Destructors don’t take any argument and don’t return anything.

 Can there be more than one destructor in a class?


No, there can only one destructor in a class with class name preceded by ~, no
parameters and no return type.

Designed by:Vasudha
• When do we need to write a user-defined destructor?
If we do not write our own destructor in class, compiler
creates a default destructor for us. The default destructor
works fine unless we have dynamically allocated memory or
pointer in class.

/*...syntax of destructor....*/
class class_name
{ public:
class_name(); //constructor created.
~class_name(); //destructor created.
}

Designed by:Vasudha
#include <iostream>
class Employee
{
public:
Employee()
{
cout<<"Constructor Invoked"<<endl;
}
~Employee()
{
cout<<"Destructor Invoked"<<endl;
}
};
int main(void)
{
Employee e1; //creating an object of Employee
Employee e2; //creating an object of Employee
return 0;
} Designed by:Vasudha
• Output:
• Constructor Invoked
• Constructor Invoked
• Destructor Invoked
• Destructor Invoked

Designed by:Vasudha
Garbage collection
• In computer science, garbage collection (GC) is a form of
automatic memory management.
• The garbage collector, or just collector, attempts to reclaim
garbage, or clears the memory occupied by objects that are
no longer in use by the program.
• Garbage collection was invented by John McCarthy around
1959 to simplify manual memory management.
• Garbage collection is a form of automatic memory
management.
• In C++ the garbage collection is implemented explicitly by using Delete
keyword and destructors.

Designed by:Vasudha
Designed by:Vasudha
Designed by:Vasudha
GC Benefits:
• Improve performance ( manages heap).
• No longer have to implement any code that
Manages the lifetime of any resources.
• It is not possible to leak resources.

Designed by:Vasudha
Meta Class
• In object-oriented programming, a meta class refers to a class
that defines or generates other classes.
• It is a class whose instances are classes. Normally a class has
an instance as an objects.
• Not all object-oriented programming languages support meta
classes.
• Meta-class is basically the set of instructions that help you
create that class.
• The metaclass is implemented by using the concept of
interfaces in language like java. In C++ meta class is
implemented by using abstract class concept.

Designed by:Vasudha
Designed by:Vasudha
INHERITANCE

UNIT 3

Designed by:Vasudha
Inheritance

• In C++, inheritance is a process in which child(derived) object acquires all


the properties and behaviors of its parent(base) object automatically.
• By using inheritance concept we can reuse, extend or modify the
attributes and behaviors which are defined in other class.
• Derived class: class which inherits the members of another class (Known
as child class ).
• Base class: the class whose members are inherited (Known as the parent
class).

Reason to implement Inheritance is :


• Code reusability: Now you can reuse the members of your parent class.
So, there is no need to define the member functions again.
• Less code is required in the class.

Designed by:Vasudha
Syntax of Derived class:
class derived_class_name : visibility-mode base_class_name
{
// body of the derived class.
}

• derived_class_name: It is the name of the derived class.


• visibility mode: The visibility mode specifies whether the
features of the base class are publicly inherited or
privately inherited. It can be public or private.
• base_class_name: It is the name of the base class.

Designed by:Vasudha
How to make a Private Member
Inheritable
• C++ introduces a third visibility modifier, i.e., protected. The member
which is declared as protected will be accessible to all the member
functions within the class as well as the class immediately derived from it.

• Public: When the member is declared as public, it is accessible to all the


functions of the program.
• Private: When the member is declared as private, it is accessible within
the class only.
• Protected: When the member is declared as protected, it is accessible
within its own class as well as the class immediately derived from it.

Designed by:Vasudha
Visibility of Inherited Members

Designed by:Vasudha
Types Of Inheritance
1. Single Inheritance: A derived class inherits from a
single base class.
2. Multiple Inheritance: A derived class inherits from
multiple base classes.
3. Multilevel Inheritance: A class inherits from
another derived class, forming a chain of
inheritance.
4. Hierarchical Inheritance: Multiple derived classes
inherit from a single base class.
5. Hybrid Inheritance: A combination of two or more
types of inheritance.

Designed by:Vasudha
Example of public, protected and
private inheritance in C++

Designed by:Vasudha
class base
{ public: int x;
protected: int y;
private: int z;
};
Class Derived1: public base
{ x is public accessible
y is protected accessible
z is not accessible
};
class Derived2: private base
{ x is private not accessible
y is private not accessible
z is not accessible
};

Designed by:Vasudha
class Derived3: protected base
{ x is protected accessible
y is protected accessible
z is not accessible
};
class Derived4: public Derived3
{ x is not accessible
y is not accessible
z is not accessible
};

Designed by:Vasudha
Designed by:Vasudha
Single Inheritance
• Single inheritance is defined as the inheritance in which a derived class is
inherited from the only one base class.

• Where 'A' is the base class, and 'B' is the derived class.

Designed by:Vasudha
int main()
#include <iostream.h>
{
increment i;
class basic_salary //BASE CLASS cout<<"Salary: "<<[Link]<<endl;
{ cout<<"Bonus: "<<[Link]<<endl;
public: int salary;
basic_salary() int Total_salary=[Link] + [Link];
{salary = 10,000;
} cout<< “Total salary=“<< Total_salary;
}; return 0;
class increment: public basic_salary }
//DERIVE CLASS
{
public: int bonus;
increment()
{ bonus = 5000;

};
Designed by:Vasudha
Multiple Inheritance
Multiple inheritance is the process of deriving a new class that
inherits the attributes from two or more classes.

Syntax of the Derived class:


class D : visibility B-1, visibility B-2, ?
{
// Body of the class;
}

Designed by:Vasudha
#include <iostream>

class num1 //parent class 1 class num2 // parent class 2


{ {
public: int a; public: int b;
public: public:
void get_a(int n) void get_b(int n)
{ {
a = n; b = n;
} }
}; };

Designed by:Vasudha
class add : public num1 , public num2
{
public: int sum;
void display()
{
cout << "The value of a is : " <<a<< endl;
cout << "The value of b is : " <<b<< endl;
sum=a+b ;
cout<<"Addition of a and b is : "<<sum;
}
};
int main()
{
add c;
c.get_a(10);
c.get_b(20);
[Link]();

return 0;
}
Designed by:Vasudha
Multilevel Inheritance
• Multilevel inheritance is a process of deriving a class from another
derived class.
• When one class inherits another class which is further inherited by
another class, it is known as multi level inheritance in C++. Inheritance is
transitive so the last derived class acquires all the members of all its base
classes.

Designed by:Vasudha
#include<iostream.h>
class num //SUPER BASE CLASS
{ protected: int a,b;
public:
void getdata()
{ cout<<"enter first number=";
cin>>a;
cout<<"enter second number=";
cin>>b;
}

protected:
void protectedfunction()
{ cout<<"\nprotected function of base class is called";
}
}; Designed by:Vasudha
class add:public num // Derived Class 1
{ public:
int add;
public:
void sum()
{ add= a+b;
cout<<"value of addition:"<<add;
}
protectedfunction();

};

Designed by:Vasudha
class percent: public add // Derived Class 2
{ public: int per;
public:

void percentage()
{ per= ((add/200)*100);
cout<<"\nvalue of a="<<a;
cout<<"\nvalue of b="<<b;
cout<<"\nvalue of sum="<<add;
cout<<"\n value of percentage="<<per;
protectedfunction();
}
};
int main()
{ percent p;
[Link]();
[Link]();
[Link]();
return 0;
}
Designed by:Vasudha
Hierarchical Inheritance
• When several classes are derived from common base class it is
called hierarchical inheritance.
• In C++ hierarchical inheritance, the feature of the base class is inherited
onto more than one sub-class.
• For example, a car is a common class from which Audi, Ferrari, Maruti etc
can be derived.

Designed by:Vasudha
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.
}
int main()
{ B obj1; //object of derived class B
C obj2; //object of derived class C
D obj3; //object of derived class D
return 0;
}
Designed by:Vasudha
C++ Hybrid Inheritance
• Hybrid inheritance in C++ is the inheritance where a class is derived from
more than one form or combinations of any inheritance.
• It Is also called as multipath inheritance.
• In short, hybrid inheritance is a combination of two or more types of
inheritance.
• For example, by implementing single and multilevel inheritances in the
same program.

Designed by:Vasudha
class A
{ // body of the class A
};

class B : public A
{ // body of the class B
};

class C
{ // body of the class C
};

class D : public B, public C


{ // body of the class D
};

Main()
{ D obj1 // object the D class is created.
return 0;
}

Designed by:Vasudha
Abstract Class
• Abstract Class is a class which contains at least one Pure
Virtual function in it.
• Abstract class can have normal functions and variables along
with a pure virtual function
• Classes that inherit the abstract class is called as concrete
classes.
• Cannot be Instantiated: You cannot create objects of an
abstract class directly. Attempting to do so will result in a
compilation error.
• Serves as a Base Class: Abstract classes are primarily used as
base classes for inheritance. Derived classes inherit from the
abstract class and must provide implementations for all its
pure virtual functions, or they too will become abstract..

Designed by:Vasudha
Key characteristics of an abstract class:
• Pure Virtual Functions: An abstract class must
contain at least one pure virtual function.
• A pure virtual function is declared by
assigning = 0 in its declaration, indicating that
it has no implementation in the base class.
• Derived classes are then required to provide
an implementation for these pure virtual
function.

Designed by:Vasudha
class number
{ public:
virtual void add() = 0;
};

• Here, the pure virtual function is:


virtual void add() = 0 ;
• the class number is an abstract class.

Designed by:Vasudha
#include<iostream.h>
class Base //Abstract base class

{ public:
virtual void show() = 0; // Pure Virtual Function
};

class Derived: public Base


{public:
void show()
{ cout << "Implementation of Virtual Function in Derived class";
}
};

Int main()
{
Derived d;
[Link]();
}

Designed by:Vasudha
class color
{ public: virtual void showcolor() = 0; // pure virtual function
};
class red:public color
{ public: void showcolor()
{ cout << "color is red"<<endl;
}
};
class blue:public color
{ public: void showcolor()
{ cout << "color is blue"<<endl;
}
};
int main()
{ red r;
blue b;
[Link]();
[Link](); } Designed by:Vasudha
Designed by:Vasudha
Relations between CLASSES
• The relationship between the classes explains
how the classes are connected to each other’s
and how they will behave.
• Mainly there are four type of relationship is
present :
 Inheritance
 Association
 Aggregation
 Composition

Designed by:Vasudha
• Inheritance:
• One class can use features from another class to access its
functionality.
• Inheritance based on IS-A Relationship.
• Inheritance is uni-directional. Inheritance is indicated by
a solid line with a arrowhead pointing at the super class.

Designed by:Vasudha
Association
• Association represents a relationship between two or
more objects where all objects have their own life
cycle and there is no owner.
• Association is based on HAS-A Relationship.
• Association can be one-to-one, one-to-many, many-
to-one, many-to-many.
• Composition and Aggregation are the two forms of
association.

Designed by:Vasudha
• In above example two separate classes Bank
and Employee are associated through their
Objects. Bank can have many employees, So it
is a one-to-many relationship.

Designed by:Vasudha
Designed by:Vasudha
Aggregation
• Aggregation is a special form of Association where all objects have their
own life cycle but there is ownership.
• This represents a-part-of relationship based on HAS-A Relationship.
• This is represented by a hollow diamond followed by a line.
• In Aggregation, both the entries can survive individually which means
ending one entity will not effect the other entity

We can take an example of relationship between Department and Teacher. A Teacher


may belongs to many departments. Hence Teacher is a part of many departments. But
if we delete a Department, Teacher Object will not destroy.

Designed by:Vasudha
Composition
• Composition is a restricted form of Aggregation in which two entities are
highly dependent on each other.
• It represents part-of-death relationship, in this both the entities are
dependent on each other.
• When there is a composition between two entities, the composed object
cannot exist without the other entity.
• This is represented by a solid diamond followed by a line.

• Here we can take another example of relationship between Building and


Room. A Building can have many Rooms but a Room cannot belong to
many Buildings. If we destroy Building, Room will be automatically
destroyed.

Designed by:Vasudha
POLYMORPHISM

UNIT 3

Designed by:Vasudha
Polymorphism in C++
• The process of representing one Thing in multiple
forms is known as Polymorphism.
• Polymorphism is derived from 2 Greek words: word
"poly" means many and “morphs” means forms. So
polymorphism means MANY FORMS

Designed by:Vasudha
Real life example of Polymorphism in
C++
• Suppose if you are in class room that time you behave like a student,
when you are in market at that time you behave like a customer, when
you at your home at that time you behave like a son or daughter, Here
one person have different-different behaviors.

Designed by:Vasudha
Designed by:Vasudha
Type of Polymorphism
• Polymorphism means more than one function with same name,
with different working.
• Polymorphism can be Compile Time and Run Time.

Compile Time Polymorphism(Static):-


• In compile time polymorphism memory will be allocated at
compile-time. Both function overloading and operator overloading
are an examples of compile time polymorphism.
• Static polymorphism is also known as early binding and static
polymorphism.
RunTimePolymorphism(Dynamic):-:-
• In run time polymorphism memory will be allocated at run-time.
Virtual function is an example of dynamic polymorphism.
• Run time polymorphism is also known as late binding and dynamic
polymorphism.

Designed by:Vasudha
Designed by:Vasudha
Compile time polymorphism
• In this method object is bound to the function call at the
compile time itself.
• In C++ programming you can achieve compile time
polymorphism in two way, which is given below;

1. Function Overloading
2. Operator Overloading.

Designed by:Vasudha
[Link] overloading
• Function Overloading in C++ can be defined as the process of
having two or more member functions of a class with the same
name, but different in parameters.
• In function overloading, the function can be redefined either by
using:
1. Different types of arguments or
2. Different number of arguments or
3. Different sequence or order of argument.

• One of the major advantages of Function overloading is that it


increases the readability of the program because we don’t need to
use different names for the same action again and again.

Designed by:Vasudha
Example:
1. These two have different number of parameters:
• sum(int num1, int num2)
• sum(int num1, int num2, int num3)

2. These two functions have different parameter type:


• sum(int num1, double num2)
• sum(int num1, int num2)

3. These two have different sequence or order of


parameters:
• sum(int num1, double num2)
• sum(double num1, int num2)

Designed by:Vasudha
WHY WE USE FUNCTION
OVERLOADING
• We use function overloading/method overloading
for the purpose of:
1. Compile time binding
2. Better Consistency
3. Better Readability

Designed by:Vasudha
Designed by:Vasudha
Designed by:Vasudha
#include <iostream.h> int main()
class show { show s;
{ void display ( ) [Link](); //function call with
{ int a = 3; no arguments
cout << a << endl; [Link](5); //function call with
} one integer argument
void display (int a ) [Link](2.3); //function call with
one floating argument
{ cout << a << endl; [Link](5,4.0f); //function call
} with one integer and one floating
void display (double a ) arguments
{ cout << a << endl; return 0;
} }
void display(int a, float b) //end of program
{ cout<< a << " , " << b <<
endl; Output
} • 3
}; • 5
• 2.3
• 5 , 4.0

Designed by:Vasudha
Designed by:Vasudha
Designed by:Vasudha
How to resolve overloading ambiguity
errors?
• If you don't want the implicit conversion sequence mapping to
throw you off, just provide functions and call them in such a
way so that the parameters are a exact match.
1. Call the function so that parameters are exact match to the
functions available.
• function(1.2f,2.2f);
• Since 1.2f and 2.2f are treated as float types they match
exactly to the float function version.

Designed by:Vasudha
[Link] Overloading
• Operator overloading is a compile-time polymorphism. It is an idea of
giving special meaning to an existing operator, without changing its
original meaning.
• We can overload the operator like (+, -, *, /, ==, <<, >>) etc., does when
applied to objects of your class.

• Goal of Operator Overloading: To redefine the behavior of an operator


so that it works with objects of a user-defined type, while still retaining
its meaning for built-in types.

• Operator that cannot be overloaded are as follows:


 Scope operator (::)
 Size of()
 member selector(.)
 member pointer selector(*)
 ternary operator(?:)
Designed by:Vasudha
Syntax:

Return type class_name operator symbol (argument_list)


{
// body of the function.
}

• class_name is the name of the class.


• operator is the keyword
• symbol is the operator which is being overloaded.

Designed by:Vasudha
program to overload the
UNARY OPERATOR (++).

Designed by:Vasudha
#include <iostream.h>
class Test
{ public: int count;
public:
Test() // constructor called
{ count=5;
}
void operator ++( )
{ count = count + 5;
}
void Display()
{ cout<<"Count: "<<count;
}
};
int main()
{ Test t;

++t; // operator function called.


[Link]();
return 0;
}
Designed by:Vasudha
• We can also redefine the same function like this
1. void operator --()
{ count = count-1;
}

Designed by:Vasudha
How to overload the
BINARY OPERATOR .
• Overloading Binary Operator: In binary
operator overloading function, there should
be one argument to be passed.
• It is overloading of an operator operating on
two operands.

Designed by:Vasudha
a program to add two object values using (+)operator
#include<iostream.h>
class sum
{ public: int x;
sum(int i) //constructor called
{ x=i;
}
void operator+(sum a) //overload (+) operator function
{ int m = x + a.x;
cout<<"The result of the addition of two objects is : "<<m;
}

};
int main()
{
sum a1(5); x + a.x;
sum a2(4);
x;
a1+a2;
return 0; a2
a1
}
Designed by:Vasudha
a program to convert positive number into negative using
(-)operator
#include <iostream.h>
Class Distance
{ private: int feet; int inches;
public:
Distance(int f, int i) // Constructor
{
feet = f;
inches = i;
}
void display() // method to display distance
{ cout << "F= " << feet << " I=" << inches <<endl;
}

Void operator-( ) // overloaded minus(-) operator


{ feet = -feet;
inches = -inches;
cout<<“new value of FEET=“<<feet;
cout<<“new value of INCHES=“<<inches;
}
};
Designed by:Vasudha
int main()
{ Distance D1(3, 4);
Distance D2(-1,10);
[Link]();
-D1;
[Link]();
-D2;
return 0;
}

Output: F= (3) I=(4 )


new value of FEET=(-3)
new value of INCHES=(-4)
F= ( -1) I=(10)
new value of FEET=(1)
new value of INCHES=(-10)

Designed by:Vasudha
Run time Polymorphism
(Function Overriding)

• Function overriding:- It is the redefinition of base class


function in its derived class with same signature i.e
return type and parameters.
• In function overriding:
 The Base class function is called the overridden
function.
 The Derive class function is called overriding function.
• The base class function must be declared as virtual
function for runtime polymorphism to happen.

Designed by:Vasudha
Virtual Function( implementation of
run time polymorphism)
• A C++ virtual function is a member function in the base class that you
redefine in a derived class.
• It is declared using the virtual keyword.
• It is used to tell the compiler to perform dynamic linkage or late binding
on the function.
• Late Binding: It happens with virtual functions where the exact function
to call is decided at runtime, depending on the actual object type. This
is slower because the program has to figure it out while running.

• Why we declare a function virtual? To let compiler know that the call
to this function needs to be resolved at runtime (also known as late
binding and dynamic linking) so that the object type is determined and
the correct version of the function is called. So, we create the pointer
to the base class that refers to all the derived objects.
Designed by:Vasudha
• IF WE NOT USE THE VIRTUAL KEYWORD: The base class
pointer contains the address of the derived class object,
always executes the base class function. This issue can only be
resolved by using the 'virtual' function.

syntax: VIRTUAL Datatype Function Name()


{ // function body
}

Designed by:Vasudha
Designed by:Vasudha
#include <iostream.h>
class Number
{
public:
Virtual void display() // display() of the base class
{
cout<<“value is a number";
}
};
class Prime: public Number
{
public:
void display() // display() of the derive class
{
cout<<“value is a prime number";
}
};
int main( )
{
Number *n; // pointer object of base class
Prime p; //object of derived class
n = &p;
n-> display(); //Late Binding occurs
return 0;
}

Output: value is a prime number Designed by:Vasudha


• In the above example, (*n) is the base class pointer. The
pointer can only access the base class members but not the
members of the derived class.
• Although C++ permits the base pointer to point to any object
derived from the base class, it cannot directly access the
members of the derived class.
• Therefore, there is a need for virtual function which allows
the base pointer to access the members of the derived class.

Base class VIRTUAL Derive class


Display()
Number Display() Prime

Direct access
Indirect access
Pointer of base
*n by the pointer
class

Designed by:Vasudha
• PROGRAM WITH VIRTUAL KEYWORD • PROGRAM WITHOUT VIRTUAL KEYWORD
#include <iostream.h> #include <iostream.h>
class Animal class Animal
{ {
public: public:
Virtual void eat() // eat() of the base void eat() // eat() of the base class
class {
{ cout<<“Animal Eat food for energy";
cout<<“Animal Eat food for energy"; }
} };
}; class Cow: public Animal
class Cow: public Animal {
{ public:
public: void eat() // eat() of the derive class
void eat() // eat() of the derive class {
{ cout<<“Cow Eat grass...";
cout<<“Cow Eat grass..."; }
} };
}; int main(void)
int main(void) {
{ Animal *a; // pointer object of base class
Animal *a; // pointer object of base class Cow c; //object of derived class
Cow c; //object of derived class a = &c;
a = &c; a->eat(); //Late Binding occurs
a->eat(); //Late Binding occurs return 0;
return 0; }
}
Output: Animal Eat food for energy
Output: Cow Eat grass...
Designed by:Vasudha
FILE & EXCEPTION HANDLING

UNIT 4

Designed by:Vasudha
Files and Streams
• To read and write from a file we are using the standard C++ library
called fstream. Let us see the data types define in fstream library is:

Designed by:Vasudha
Designed by:Vasudha
File Handling Operations
For achieving file handling in C++ we need follow following steps
1. Naming a file
2. Opening a file
3. Reading data from file
4. Writing data into file
5. Closing a file

Designed by:Vasudha
Defining and Opening a File
• The function open() can be used to open multiple files that use the same
stream object.

Designed by:Vasudha
Modes of Opening a file
• We need to tell the computer the purpose of opening our file.
e.g.-
• fstream filein("[Link]", ios::in);
• fstream str("[Link]", ios::in | ios::out);
These are the different modes in which we can open a file:

Designed by:Vasudha
#include <iostream.h>
#include <fstream.h>
int main()
{
fstream file;
[Link] ("[Link]", ios::out | ios::in );
[Link]();
return 0;
}

Designed by:Vasudha
Closing a File
• A file must be close after completion of all operation related to file. For
closing file we need close() function.

Designed by:Vasudha
Reading &Writing in a FILE

Designed by:Vasudha
Writing in a file…

Designed by:Vasudha
File is created in bin(folder)

Designed by:Vasudha
Demo file data

Designed by:Vasudha
Reading from a file

Designed by:Vasudha
Namespaces
• Namespaces in C++ is a declarative region that is used to organize too
many classes so that it can be easy to handle the application.

➢ Defining a Namespace:
• You define a namespace using the namespace keyword followed by the
namespace name and a block containing its members.

➢ Accessing Namespace Members:


1. For accessing the members of a namespace, we need to use
Eg: MyNamespace::myVariable=10;
MyNamespace::myFunction();
2. We can use using keyword so that we don't have to use complete name
all the time.
Eg: using namespace std;

• In C++, global namespace is the root namespace. The global::std will


always refer to the namespace "std" of C++ Framework.
Designed by:Vasudha
#include <iostream.h>
using namespace std;
namespace First
{
void display()
{
cout<<" First Namespace is created"<<endl;
}
}
namespace Second
{
void show()
{
cout<<"Second Namespace is created"<<endl;
}
}
int main()
{
First::display();
Second::show();
return 0;
}
OUTPUT: First Namespace created
Second Namespace created
Designed by:Vasudha
Designed by:Vasudha
Exception Handling
• Exception handling in C++ is a mechanism to detect and manage runtime
errors in a structured way.
• Examples of runtime errors are.
1. Division by zero.
2. Accessing invalid memory.
3. File I/O failures.

• In C++, exception is an event or object which is thrown at runtime.


• All exceptions are derived from (std::exception class).

Advantage
• It maintains the normal flow of the application.

To perform exception handling we use following blocks:


• Try Block
• Throw Block
• Catch Block
Designed by:Vasudha
How Exception Handling Works in C++
(Try & Catch Block)
1. Try Block:
• The try block contain statements which may generate
exceptions..
1. Throw Block:
• Throwing an Exception : When an exception occur in try
block, it is thrown to the catch block using throw keyword, to
signal an exception.
3. Catch Block:
• The catch block defines the action to be taken, when an
exception occur..
• Catching an Exception : The program searches for a
matching catch block to intercept and handle the thrown
exception.
• Handling the Exception : The catch block contains the logic
to respond to the error, allowing the program to recover or
terminate gracefully. Designed by:Vasudha
• Syntax:
try
{ //code throw parameter;
}
catch(exceptionname ex)
{ //code to handle exception
}

Designed by:Vasudha
try/catch example

Designed by:Vasudha
//program for negative number checking…..
#include <iostream.h>
using namespace std;
int main()
{
int x = -20;
try
{
if (x < 0)
{ throw x;
}
else
{ cout<<“value is positive”<<x;
}
}
catch (int x)
{
cout << "Exception Caught value of x is less than zero:"<<x;
}

return 0;
} Designed by:Vasudha
Designed by:Vasudha
//program for checking number divided by (ZERO)….
#include<iostream>
using namespace std;
int main()
{ int num1=10, num2=0; float num3;
try
{ if(num2==0)
{ throw(num2);
}

else
{ num3=num1/num2;
cout<<"outcome :"<<num3;

}
}
catch(int exc)
{ cout<<"division by zero is not possible. Please try again with
different value of variables";
}
} Designed by:Vasudha
Designed by:Vasudha
program for checking
“Array out of bound Exception”.

Designed by:Vasudha
#include<iostream>
using namespace std;
int main()
{
int arr[ ]={10,20,30,40,50};
int size=sizeof(arr) / sizeof(arr[0]);
int index;
cout<<"enter array index";
cin>>index;
try { if (index < 0 || index >=size)
{ throw "Error: Custom array index out of bounds!";
}
else
{ cout << "Element at index " << index << ": " << arr[index] << endl;
}
}
catch (const char* msg)
{ cout << msg << endl;
}
return 0; Designed by:Vasudha
}
Generic programming (Templates)
• A template is a powerful tool for creating generic classes or
functions.
• Key feature of templates :Avoid code duplication by allowing one
function or class to work with multiple data type.
• Templates can be defined using the keywords "template" and
"typename“.
Syntax: template <typename T>
➢ template keyword is used to define that the given entity is a
template.
➢ typename keyword is used to define template parameters which
are nothing but type.

Templates can be represented in two ways:


• Function templates
• Class templates
Designed by:Vasudha
[Link] Template
• A function template is used to write a generic code for
function that can work with different data types at a time.
• The type of the data that the function will operate on
depends on the type of the data passed as a parameter.

Syntax of Function Template


template < typename Ttype>
Ttype func_name(parameter_list)
{
// body of function.
}

Designed by:Vasudha
// Creating Template function to return maximum of two values:

#include<iostream>
using namespace std;

template <typename T>

T Max(T x, T y) //Template function Max is created


{ return (x > y) ? x : y;
}

int main()
{
cout << "Max is:"<< Max<int>(8, 7) << endl;
cout << "Max is:" << Max<double>(6.5, 9.5) << endl;
cout << "Max is:" << Max<char>('v’, 'y') << endl;
}
return 0;
Designed by:Vasudha
#include<iostream>
using namespace std;
template<typename T>
T add(T a, T b) // template function create
{
T result=a+b;
return result;
}

int main()
{
int i=2,j=3,s=0;
float m=2.3,n=1.2,a=0;
s = add(i,j);
cout<<"Addition of i and j is :"<<s<<endl;
a= add(m,n);
cout<<"Addition of m and n is :"<<a<<endl;
return 0;
} Designed by:Vasudha
[Link] TEMPLATE
Class Template:-
• class templates are useful when a class defines something that is
independent of the data type.
• When a class uses the concept of Template, then the class is
known as generic class.
Syntax
template<class Ttype>
class class_name
{
.
.
}
Ttype is a placeholder name which will be determined when the class is
instantiated. We can define more than one generic data type using a comma-
separated list. The Ttype can be used inside the class body.

Designed by:Vasudha
• Now, we create an instance of a class i.e. OBJECT
SYNTEX
class_name<type> ob;
Where:
• class_name: It is the name of the class.
• type: It is the type of the data that the class is operating on.
• ob: It is the name of the object.

Designed by:Vasudha
#include <iostream>
template<class T>
class Addition
{
public:
T add(T num1, T num2)
{
cout << "Addition of num1 and num2 : " << num1+num2<<endl;
}

};

int main()
{
Addition<int>a1;
Addition<double>a2;
[Link](10,20);
[Link](5.5,4.5);
return 0;
}
Designed by:Vasudha
Designed by:Vasudha
How to create User define Header file..
• Write a program which you want to store in a header file:
int sum(int a, int b)
{ return (a + b);
}

• Save this file by using name:-”sum.h” extension.

• Create another program and Include your header file with “#include” in your
program.

#include <iostream.h>
#include <sum.h>
using namespace std;

int main()
{ int a = 10, b = 20; // Given two numbers
cout << "Sum is: "<< sum(a, b) << endl;
} Designed by:Vasudha

You might also like