Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 250

Introduction to C++

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
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.
• 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 INCREMENT 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 December 2020 as ISO/IEC
14882:2020 (informally known as C++20).
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.
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++” .
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.
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.
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.
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.
OBJECT ORIENTED
METHODOLOGY USING C++
SOFTWARE 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...
Procedure-Oriented Programming(POP)

• Procedure: Sequence of things or statements.


• In POP basically consisting of writing a list of
instructions for the computer to follow ,and
organizing these instructions into groups known as
FUNCTIONS.
• It is a top-down approach.
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.
Object Oriented Paradigm
• The object oriented languages supports several of
the OOP’s concepts to claim that they are object
oriented.
• 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.
Object-Based programming
language
• This programming language support the encapsulation and
object identity. Major features that are required for object-
based programming are:
1. Data encapsulation
2. Data hiding and access mechanism
3. Automatic initialization and clear-up of object
4. Operator overloading

• These languages doesn’t support inheritance and dynamic


binding
Object-Oriented programming
languages
• These languages incorporates all the features
of object-based programming along with the
two additional features i.e. inheritance and
dynamic binding.
• Languages that support these features are C+
+, Smalltalk, Pascal, Java etc.
Oop’s Concept
• Object oriented programming(Oop’s) aims to implement real
world entities like inheritance, data 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
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.
Understanding “Object and Class”
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 members of the class
can be accessed through object.
• Before create an objects and use them in C++, we first need
to create a classes.
CLASSES
• A Class is a user defined data-type which has Data Members
and Member Functions.
• Data members are the data variables and member functions
are the functions used to manipulate these variables and
together these data members and member functions defines
the properties and behavior of the objects in a Class.
• For Example: Consider the Class of MOBILE PHONE. There
may be many with different names and brand but all of them
will share some common properties like size, camera, calling,
messaging etc… and methods like lock and unlock, video
calling method etc…
CLASS DIAGRAM
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” .
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.
• Those classes which uses the concept of data
abstraction, are known as ABSTRACT DATA
TYPE( ADT).
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.
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 an 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.
Single Inheritance Multiple Inheritance Multilevel Inheritance

Hierarchical Inheritance Hybrid Inheritance


POLYMORPHISM
• The word polymorphism means poly means MANY and morph
means FORM i.e. One name and many forms.
• In simple words, we can define polymorphism as the ability of a
message to be displayed in more than one form.
• Real life example of polymorphism, a person at a same time can
have different characteristic.
• Eg. Like a man at a same time is a father, a business man, a
employee. So a same person can have different behavior in
different situation.

In C++ polymorphism is mainly divided into two types:


• Compile time Polymorphism
• Runtime Polymorphism
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 func(int x) , void func(double x), void func(int x, int y)

• 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. So a single operator ‘+’ when placed
between integer operands , adds them and when placed between string
operands, concatenates them.
1. Runtime polymorphism: This type of polymorphism is
achieved by Function Overriding.

• Function overriding on the other hand occurs when a derived


class has a definition for one of the member functions of the
base class. That base function is said to be overridden.
Dynamic binding

• Binding refer to the linking of a procedure call


to the code to be executed in response to the
call.
• It is also known as late binding or runtime
binding.
• It is also associated with the polymorphism
and inheritance.
Difference Between C AND C++
SEQ .N Basis of C C++
O 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
Structure of C++ programs and its
Operators
Basic Structure of A Complete C++ Program

1. Documentation Section
• comments.(// or /*………..*/)
• Preprocessor Directives
• Global Declaration Section
• Class declaration or definition
• Data members declare.
• Member function declare and define.
• Main Function declaration.
• Object declaration part.
• Accessing member functions (using dot operator).
Documentation 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".

2. Multiple Line Comment: Comment can be given in


multiple lines starting by using "/*" and end with "*/".
• Example: /* Text Line ………… */
Preprocessor 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“

•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"
Global 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];
Class 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".
• For example: class Circle (Here Circle is the class name).

• 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

• Member Functions
• These are the various operations that can be performed to data members of that
class. We can declare any number of member functions of any type in a class.
Member functions are access using object and dot operator.
• example: void read(), void display()
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:
 1. Private: 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 boundary.
 2. Public: Public members are accessible from outside the class
boundary.
 3.Protected: 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).
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 (c1 is the object of the class Circle).

• Accessing member functions (using dot operator)


• The member function define in the class are access by using dot (.)
operator.
• Obj1. member function();
• example: c1.read();
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(Data members)

Class Display Class definition (Circle class is created)


{ Int n2; Local variable (Data Member)

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;

}
};
Int main ( ) Main program starts
{
clrscr();
Display d1; Object of the class is created
d1.detdata( ); Member functions is accessed through object.
d1.showdata( );
getch( );
return 0;
}
OPERATORS IN C++
Scope resolution operator in C++
• Scope resolution operator is used to get the hidden names due to
variable scopes so that you can still use them.
• 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:
#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;
}
2) To define a function outside a class.
#include<iostream>
class A
{
public:

void fun(); // Only declaration


};

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


{
cout << "fun() called";
}

int main()
{ A a;
a.fun();
return 0;
}
Memory allocated/de allocated in
C++?
• 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 freeing
the memory in a better and easier way.
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 to use new operator: To allocate memory of any data type, the
syntax is:
• 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;
1. Initialize memory: We can also initialize the memory using new operator:
• Example: int *p = new int(25);
float *q = new float(75.25);

• 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.
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;
#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;
Cin and cout
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”;
Standard input stream (cin):
•In C++ cin statement is the instance of the
class iostream 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;
Functional Decomposition
• Functional Decomposition is the process of taking a complex
process and breaking it down into its smaller, simpler parts.
• Each of which can be broken down further. Once you've
reached the most decomposed pieces of a subsystem, you can
think about how to start coding those pieces.
Benefit of functional decomposition:-
• Is that once you start coding, you are working on the simplest
components you can possibly work with for your application.
Therefore developing and testing those components becomes
much easier.
CLASS AND OBJECT

UNIT 2
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.”
• Data Hiding is the one most important OOP mechanism.
Which is hide the details of the class from outside of the class.
• Which mainly includes:-
 Encapsulation
 Abstraction
• private, public & protected are three types of access specifies
available within a class. the data within a class is private &
the functions are public. The data is hidden, so that it will be
safe from accidental manipulation.
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
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.
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
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)
{…….
}
Passing Parameters to a function
by VALUE or by REFERENCE

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.
#include <iostream> Call by Value
#include <conio.h>
void swap(int,int);
int main()
{
int a = 45, b = 35;
cout << "Before Swap\n“<<endl;
cout << "a = " << a << " b = " << b << endl;

swap(a, b);

cout << "After Swap with call by value”<<endl;


cout << "a = " << a << " b = " << b << endl;
}

void swap(int x, int y)


{
int z = x;
x = y;
y = z;
cout << “x = " << x << " y = " << y ;
}
2. Call by reference(Pass by reference)

• It allows a function to modify a variable


without having to create a copy of it. We
have to declare reference variables.
• The memory location of the passed variable
and parameter is the same and therefore,
any change to the parameter reflects in the
variable as well.
#include<iostream.h>
#include<conio.h>
void swap(int ,int );
void main()
{ int a=10,b=20;
clrscr();
cout<<"Value of A is: "<<a;
cout<<"\nValue of B is : "<<b;

swap(a,b);
//Swapping by PASS BY POINTER
#include<iostream.h>
#include<conio.h>
void swap(int *,int *);
void main()
{ int a=10,b=20;
clrscr();
cout<<"Value of A is: "<<a;
cout<<"\nValue of B is : "<<b;

swap(&a,&b);
INLINE FUNCTION
• C++ provides an inline functions to reduce the function call overhead.
• Inline function is a function that is expanded in line when it is called.
• When the inline function is called whole code of the inline function gets
inserted or substituted at the point of inline function call.
• This substitution is performed by the C++ compiler at compile time.
• Inline function may increase efficiency if it is small.
• SYNTEX:
inline return-type function-name(parameters)
{
// function code;
}
#include <iostream>
int main()
{ cout << “Maximum is=“<<Max(20,10) << endl;
cout << "Maximum is="<< Max(400,200) << endl;
return 0;
}
inline int Max(int x, int y)
{ return (x > y)? x : y;
}
• Inlining is only a request to the compiler, not a command. Compiler
can ignore the request for inlining. Compiler may not perform
inlining in such circumstances like:

1) If a function contains a loop. (for, while, do-while)


2) If a function contains static variables.
3) If a function is recursive.
4) If a function return type is other than void, and the return
statement doesn’t exist in function body.
5) If a function contains switch or goto statement.
#include <iostream.h>
Class operation
{
int a,b,add; int main()
public: {
void getdata();
void sum(); operation s;
}; s.getdata();
inline void operation :: getdata()
{
s.sum();
cout << "Enter first value:"; return 0;
cin >> a;
cout << "Enter second value:"; }
cin >> b;
}

inline void operation :: sum()


{
add = a+b;
cout << "Addition of two numbers: " << add << "\n";
}
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.”
STATE:-
• An object's state is defined by the attributes of the object and
by the values these have.
• An attribute is a feature of an object, which distinguishes it
from other kinds of objects. For example, one of the
attributes of any car object is that it is capable of movement –
it has a speed.
• An attribute is usually something static. This means that it
cannot be removed or altered without changing the essential
nature of the object to which it belongs.
BEHAVIOR:-
• Behavior is how an object acts and reacts in terms of its
state changes and message passing.”
• A few kinds of operations that a client may perform on
an object:
– Modifier: alters the state of an object.
• E.g. karan.setNetWorth(25000);
– Selector: accesses the state of an object, but does
not alter it.
• E.g. age = s.getAge();
– Constructor: creates an object and initializes its state.

– Destructor: destroys an object (frees its memory).


IDENTITY:-
• Identity is that property of an object which distinguishes
it from all others.
• Every instance of a class has its own memory to hold its
state.
Passing Object as an argument in
C++ function
• As we know that, 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);
• This is implemented in:-
 when we want to initialize all data members
of an object with another object,
 we can pass objects and assign the values of
supplied object to the current object.
 For complex or large projects, we need to use
objects as an argument or parameter.
// C++ program to calculate the average marks of two students
#include<iostream>
using namespace std;
class Student
{ public: double marks;
void setmarks(double m)
{ marks = m;
}
Void calculateAverage(Student s1, Student s2) // function has objects as
parameters
{ marks = (s1.marks + s2.marks)/2;
cout << "Average Marks = " << marks <<endl;
}
};
int main()
{ Student S1,S2,S3;
S1.setmarks(88.0);
S2.setmarks(56.0);
#include <iostream> E1.a = 30; E2.a = 70; E3.a = 0; E4.a =
using namespace std; 0;
class Example
{ public: int a; cout << "Initial Values \n";
Example add(Example Ea, Example Eb) cout << "Value of object 1: " << E1.a
{ Example Ec;
<< ", \nobject 2: " << E2.a
Ec.a = Ea.a + Eb.a;
<< ", \nobject 3: " << E3.a
return Ec;
<< "\n";
}
};
E3=E3.add(E1, E2);
E4=E3;

cout << "New values \n";


cout << "Value of object 1: " << E1.a

<< "\nobject 2: " << E2.a


<< "\nobject 3: " << E3.a
<< "\nobject 4: "<<E4.a
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 or object.
• As an array is a collection of similar type, therefore an array
can be a collection of class type.
SYNTEX:
• ClassName ObjectName[Number of Objects];
class employee
{ 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;

}
};
void main()
{
employee e1,e2,e3;
e1.getdata(); //first employee data inserted.
e1.putdata(); //first employee data printed.
e2.getdata(); //second employee data inserted.
e2.putdata(); //second employee data printed.
e3.getdata(); //third employee data inserted.
e3.putdata(); //third employee data printed.
getch();
}
void main()
{ int i;
employee e[3]; //Creating Array of 3 Employees
for(i=0;i<3;i++)
{ cout<<"\n Enter details of "<<" Employee";
e[i].getdata();
}
cout<<"\nDetails of Employees";
for(i=0;i<3;i++)
{ e[i].putdata();
}
}
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 method of another class
b) A global function
Declaration of friend function in C++:
class class name
{ ... .. ... friend return type function name(class object); ... .. ...
}
• Argument of the function is the class object.
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 cant be inherited.
#include <iostream>
class Box
{ double width;
public:
void setWidth( )
{ cout<<“enter the value of width”;
cin>>width;
}
friend void printWidth( Box );
};
void printWidth( Box b) // friend function definition
{
cout << "Width of box : " << b.width <<endl;
}
int main()
{ Box b; // Main function for the program
b.setWidth();
printWidth( b);
return (0);
}
Constructors in C++
What is constructor?
• A constructor is a special member function of the class which has the
same name as that of the class and it does not have a return type.
• A constructor in C++ is a special method that is automatically called when
an object of a class is created.
How constructors are different from a normal member function?
• Constructor has same name as the class itself.
• Constructors don’t have return type.
• A constructor is automatically called when an object is created.
• A constructor can be parametrized or not.
• If we do not specify a constructor, C++ compiler generates a default
constructor for us (expects no parameters and has an empty body).
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.
#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;
d.display();
return (0);
}
#include <iostream>
class construct
{
public:
int a, b;
construct() // Default Constructor
{
a = 10;
b = 20;
}
};
int main()
{
construct c;
cout << "a: " << c.a << endl << "b: " << c.b;
return 0;
}
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 various data elements of different objects
with different values when they are created.
– It is used to overload constructors.
Can we have more than one constructors in a class?
Yes, It is called Constructor Overloading.

Syntex:
class Name(parameter list)
{
}
#include <iostream.h>
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 function called
{ cout<<"The value of a is"<<a<<endl;
}
};
// 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;
}
};
int main()
{
Wall wall1(10.5, 8.6);
Wall wall2(8.5, 6.3);
cout << "Area of Wall 1: " << wall1.Area() << endl;
cout << "Area of Wall 2: " << wall2.Area() << endl;
return 0;
}
Copy Constructor:
• The copy constructor is a constructor which creates an object by
initializing it with an object of the same class, which has been created
previously.
The copy constructor is used to −
• Initialize one object from another of the same type.
• Copy an object to pass it as an argument to a function.
• Copy an object to return it from a function.

Syntax : ClassName (const Class Name &old_obj);


class A
{
A(const A &x) // copy constructor.
{
// copyconstructor.
}
}

copy constructor can be called in the following ways:


#include <iostream>
class show
{ public: int x;
show(int a)
{ x=a;
}
show(const show &i)/ /copy constructor
is created
{x=i.x;
}
};
int main()
#include <iostream> { Wall wall1(15.5, 10.6);
class Wall Wall wall2 = wall1;
{ private: double length;
cout << "Area of Wall 1: "
double height; << wall1.calculateArea()
public: << endl;
Wall(double len, double
hgt) cout << "Area of Wall 2: "
{ length = len; << wall2.calculateArea();
height = hgt;
}
Wall(Wall &obj) return 0;
{ length = }
obj.length;
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.
• 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. When a class contains a pointer to memory
allocated in class, we should write a destructor to release
memory before the class instance is destroyed. This must be
done to avoid memory leak.

/*...syntax of destructor....*/
class class_name
{ public:
class_name(); //constructor created.
~class_name(); //destructor created.
}
#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;
}
• Output:
• Constructor Invoked
• Constructor Invoked
• Destructor Invoked
• Destructor Invoked
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.
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.
GC Algorithm(Working Concept):
• Each application has a set of roots.
• Roots identify storage location which refers to
object on the managed heap or the objects
that are set to be null
Metaclass
• In object-oriented programming, a metaclass is a class whose
instances are classes. Just as an ordinary class defines the behavior
of certain objects, a metaclass defines the behavior of certain
classes and their instances.
• The attributes added to this class are accessible to all its
members.
• Not all object-oriented programming languages support meta
classes.
• meta-class is basically the set of instructions that help you
create that class. This is often used when you want to change
the default behavior of classes.
• 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.
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 the mathematical model with a collection of operation defined


on that model.
• ADT is concerns only with what the data is represented and not
with how it will be constructed.
• It is a set of objects and operations like insert, delete, search, sort
etc.
.
ADT IN C++
• Abstract Data type (ADT) is a type (or class) for objects whose
behavior is defined by a set of value and a set of operations.
• The definition of ADT only mentions what operations are to
be performed but not how these operations will be
implemented.
• It does not specify how data will be organized in memory and
what algorithms will be used for implementing the
operations.
• It is called “abstract” because it gives an implementation-
independent view. The process of providing only the
essentials and hiding the details is known as abstraction.
ADT consist of following three parts:
1. DATA: describe the structure of data used in ADT.
2. OPERATIONS: describe the valid operations for ADT.
3. ERROR: Describes how to deal with the errors that can be
occur
Implementation Of ADT:
• It means writing a program in a programming language.
• Implementation of ADT includes choosing a particular Data
Structure( array, stack, queue etc)
INHERITANCE

UNIT 3
C++ Inheritance
• In C++, inheritance is a process in which one object acquires all the
properties and behaviors of its parent object automatically.
• By using inheritance concept we can reuse, extend or modify the
attributes and behaviors which are defined in other class.
• In C++, the class which inherits the members of another class is called
derived class and the class whose members are inherited is called base
class. The derived class is the specialized class for the base 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 again.
• Less code is required in the class.
Base Classes:-
• Known as the parent class
Derived Classes:-
• Known as child class which is defined as the
class derived from the base class and inherit it
features.
Types Of Inheritance
1. Single inheritance
2. Multiple inheritance
3. Hierarchical inheritance
4. Multilevel inheritance
5. Hybrid inheritance
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.
How to make a Private Member
Inheritable
• The private member is not inheritable. If we modify the visibility mode by making
it public, but this takes away the advantage of data hiding.
• 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.
Visibility of Inherited Members
Example of public, protected and
private inheritance in C++
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
};
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
};
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.
#include <iostream>
using namespace std;
class basic_salary
{
public: int salary = 10,000;
};
class increment: public basic_salary
{
public: int bonus = 5000;

};
int main(void)
{
increment p1;
cout<<"Salary: "<<p1.salary<<endl;
cout<<"Bonus: "<<p1.bonus<<endl;
cout<<“Total_salary: "<<p1.salary+p1.bonus<<endl;
return 0;
}
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.
#include <iostream> class add: public
using namespace std; num
class num {
{
public:
public:
int a;
int s;
int b; public:
public: void sum()
void get_data(int n,int m) {
{ s = a+b;
a = n;
cout<<“sum=”<<s;
b= m;
}
}
}; };
class percent : public add
{
public: int per;
void display()
{
cout << "The value of a is : " <<a<< endl;
cout << "The value of b is : " <<b<< endl;
cout<<"Addition of a and b is : "<< s;
per = (s/200)*100;
cout << "The percentage is : " <<per<< endl;
}
};
int main()
{
percent p;
p.get_data(50,70);
p.sum();
p.display();

return 0;
}
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;
}
#include <iostream>
using namespace std;

class num1 //parent class 1


class num2 // parent class 2
{
{
public:
public:
int a;
int b;
public:
public:
void get_a(int n)
void get_b(int n)
{
{
a = n;
b = n;
}
}
};
};
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);
c.display();

return 0;
}
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.
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;
} //end of program
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.
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;
}
Abstract Class
• Abstract Class is a class which contains at least one Pure Virtual function
in it.
• Abstract classes are used to provide an Interface for its sub classes.
• Abstract class can have normal functions and variables along with a pure
virtual function
• Classes inheriting an Abstract Class must provide definition to the pure
virtual function, otherwise they will also become abstract class.
• Abstract classes are essential to providing an abstraction to the code to
make it reusable and extendable.
• Abstract classes cannot be used to instantiate objects(no object is
created).
• Classes that inherit the abstract class is called as concrete classes.
Use of Abstract class
• The purpose of an abstract class is to define a common protocol for a set
of concrete subclasses.
• This is useful when defining objects that share code, abstract ideas, etc.
• The main idea here is code reuse and proper partitioning across classes. It
makes more sense to define a function once in a parent class and use it
again and again in all the derive class.
Pure Virtual Functions in C++
• Pure virtual Functions are virtual functions with no definition.
• They start with virtual keyword and ends with = 0.
• Here is the syntax for a pure virtual function,
• virtual void function Name() = 0;
class number
{ public:
virtual void add() = 0;
};

• Here, the pure virtual function is:


virtual void add() = 0
• the class number is an abstract class.
//Abstract base class
class Base
{ public:
virtual void show() = 0; //
Pure VirtualFunction
};
class Derived:public Base
{public:
void show()
{ cout << "Implementation of Virtual
Function in Derived class";
}
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;
r.showcolor();
b.showcolor();
}
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
• 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.
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.
• 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.
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.
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.
POLYMORPHISM

UNIT 3
Polymorphism in C++
• The process of representing one Thing in multiple
forms is known as Polymorphism.
• Polymorphism is derived from 2 Greek words: poly
and morphs.
• The word "poly" means many and “morphs” means
forms. So polymorphism means MANY FORMS
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.
Type of Polymorphism
• Polymorphism means more than one function with same name, with
different working.
• Polymorphism can be static or dynamic.
Static Polymorphism:-
• In static polymorphism memory will be allocated at compile-time. Both
function overloading and operator overloading are an examples of static
polymorphism.
• Static polymorphism is also known as early binding and compile-time
polymorphism.
Dynamic Polymorphism:-
• In dynamic polymorphism memory will be allocated at run-time. Virtual
function is an example of dynamic polymorphism.
• Dynamic polymorphism is also known as late binding and run-time
polymorphism.
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;
• Function Overloading And Operator Overloading.
Function 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
 Different types of arguments or
 Different number of arguments or
 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.
Example:
1.These two have different number of parameters:
•sum(int num1, int num2)
•sum(int num1, int num2, int num3)

•These two functions have different parameter type:


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

•These two have different sequence or order of


parameters:
•sum(int num1, double num2)
•sum(double num1, int num2)
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
call with one integer
#include <iostream.h> argument
class show s.display(2.3);
{ void display ( ) //function call with one
{ int a = 3; floating argument
cout << a << endl; s.display(5,4.0);
//function call with one
}
integer and one floating
void display (int a ) arguments
{ cout << a << endl; return 0;
} }
void display (double a ) //end of program
{ cout << a << endl;
} Output
void display(int a, float • 3
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.
2.Operators Overloading
• Operator overloading is a compile-time polymorphism in which the
operator is overloaded to give user defined meaning to them.
• Operator overloading is used to overload or redefines the meaning of
most of the operators available in C++.
• It is used to perform the operation on the user-defined data type.
• The advantage of Operators overloading is to perform different operations
on the same operand.
• Operator that cannot be overloaded are as follows:
 Scope operator (::)
 Size of()
 member selector(.)
 member pointer selector(*)
 ternary operator(?:)
Syntax of Operator Overloading:

Return type class_name operator symbol (argument_list)


{
// body of the function.
}
• class_name is the name of the class.
• operator symbol is an operator function where symbol is the
operator being overloaded, and the operator is the keyword.

• What is the difference between operator functions and normal


functions?
Operator functions are same as normal functions. The only
differences are, name of an operator function is always operator
keyword followed by symbol of operator and operator functions
are called when the corresponding operator is used.
Following is an example of global operator function.
program to overload the
UNARY OPERATOR (++).
#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.
t.Display();
return 0;
}
• We can also redefine the same function like this
1. void operator ++()
{ count = count+1;
}
2. void operator ++()
{ count = count-100;
}
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.
a program to generate complete number 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() x + a.x;
{
sum a1(5); x;
sum a2(4);
a1 a2
a1+a2;
return 0;
}
Output:
• The result of the addition of two objects is : 9
minus(-) operator overload
#include <iostream.h>
using namespace std;
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;
}
};
int main()
{ Distance D1(3, 4);
Distance D2(-1,10);
D1.display();
-D1;
D2.display();
-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)
Late binding or Run time binding
or Dynamic linkage
• In late binding function call is resolved during runtime.
• In this compiler determines the type of object at runtime, and
then binds the function call.
Overriding(RUN Time
polymorphism )
• Overriding:- is the phenomena where one class function
overrides the definition of the other class function of the
same name.
• Function overriding:- It is the redefinition of base class
function in its derived class with same signature i.e return
type and parameters.
• It can only be implemented in the derived class.
• In function overriding, the function in parent class is called
the overridden function and function in child class is called
overriding function
//example of function overrididng….
#include<iostream.h>
Class a
{ public: void display()
{ cout << “base class display function";
}
};
Class b:public a
{ public: void display()
{ cout << “derived class display function";
}
};
aANIMAL BASE CLASS

Eat food for energy eat()


DERIVE
CLASS

DOG COCOW GOAT

eat() BREAD for energy eat() GRASS for energy eat() LEAVES for energy
#include <iostream.h>
class Animal
{
public:
void eat() // eat() of the base class
{
cout<<“Animal Eat food for energy";
}
};
class Dog: public Animal
{
public:
void eat() // eat() of the derive class
{
cout<<“Dog Eat bread...";
}
};
int main(void)
{
Dog d;
d.eat(); Output: Dog Eat bread...
return 0;
}
• If we want to print base class function also then we have to do this.
int main()
{
animal a; //Base class object
dog d; //Derived class object
a.eat();
d.eat();
}

Output: Animal Eat food for energy


Dog Eat bread...
#include <iostream.h> #include <iostream.h>
class Animal class Animal
{
{
public:
public:
void eat() // eat() of the base class
void eat() // eat() of the base class
{
{
cout<<“Animal Eat food for energy";
cout<<“Animal Eat food for energy";
}
}
};
};
class Goat: public Animal
class Cow: public Animal
{
{
public:
public:
void eat() // eat() of the derive class
void eat() // eat() of the derive class
{
{
cout<<“Goat Eat leaves...";
cout<<“Cow Eat grass...";
}
}
};
};
int main(void)
int main(void) {
{ Goat g;
Cow c; g.eat();
c.eat(); return 0;
return 0;
}
}
• Output: Goat Eat leaves..
• Output: Cow Eat grass..
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.
• There is a necessity to use the single pointer to refer to all the objects
of the different classes. So, we create the pointer to the base class that
refers to all the derived objects.
• A 'virtual' is a keyword preceding the normal declaration of a function.
• 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.
• There is a necessity to use the single pointer to refer to all the
objects of the different classes. So, we create the pointer to
the base class that refers to all the derived objects. But, when
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
}
#include <iostream.h>
class Animal
{
public:
Virtual void eat() // eat() of the base class
{
cout<<“Animal Eat food for energy";
}
};
class Dog: public Animal
{
public:
void eat() // eat() of the derive class
{
cout<<“Dog Eat bread...";
}
};
int main(void)
{
Animal *a; // pointer object of base class
Dog d; //object of derived class
a = &d;
a-> eat(); //Late Binding occurs
return 0;
}

Output: Dog Eat bread...


• In the above example, (*a) 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 Derive class


ANIMAL VIRTUAL Eat() Eat() DOG

Direct access
Indirect access
Pointer of base
*a by the pointer
class
• 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 class void eat() // eat() of the base class
{ {
cout<<“Animal Eat food for energy"; cout<<“Animal Eat food for energy";
} }
}; };
class Dog: public Animal class Dog: public Animal
{ {
public: public:
void eat() // eat() of the derive class void eat() // eat() of the derive class
{ {
cout<<“Dog Eat bread..."; cout<<“Dog Eat bread...";
} }
}; };
int main(void) int main(void)
{ {
Animal *a; // pointer object of base class Animal *a; // pointer object of base class
Dog d; //object of derived class Dog d; //object of derived class
a = &d; a = &d;
a->eat(); //Late Binding occurs a->eat(); //Late Binding occurs
return 0; return 0;

} }

Output: Dog Eat bread...


Output: Animal Eat food for energy
FILE & EXCEPTION HANDLING

UNIT 4
Files and Streams
• In C++ programming we are using the iostream standard library, it
provides cin and cout methods for reading from input and writing to
output respectively.
• 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:
How to achieve File Handling
For achieving file handling in C++ we need follow following steps
• Naming a file
• Opening a file
• Reading data from file
• Writing data into file
• Closing a file
Defining and Opening a File
• The function open() can be used to open multiple files that use the same
stream object.
Modes of Opening a file
• We need to tell the computer the purpose of opening our file.
• For e.g.- to write on the file, to read from the file, etc.
• These are the different modes in which we can open a file.
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream file;
file.open ("example.txt", ios::out | ios::in );
return 0;
}
Closing a File
• A file must be close after completion of all operation related to file. For
closing file we need close() function.
Reading &Writing in a FILE
Writing in a file…
File is created in bin(folder)
Demo file data
Reading from a file
Namespaces
• Namespaces in C++ are used to organize too many classes so that it can be
easy to handle the application.
• For accessing the class of a namespace, we need to use
namespacename::classname. We can use using keyword so that we don't
have to use complete name all the time.
• In C++, global namespace is the root namespace. The global::std will
always refer to the namespace "std" of C++ Framework.
#include <iostream.h>
using namespace std;
namespace First
{
void sayHello()
{
cout<<"Hello First Namespace"<<endl;
}
}
namespace Second
{
void Hello()
{
cout<<"Hello Second Namespace"<<endl;
}
}
int main()
{
First::sayHello();
Second::Hello();
return 0;
}
OUTPUT: Hello First Namespace
Hello Second Namespace
Exception Handling
• Exception Handling in C++ is a process to handle runtime errors.
• We perform exception handling so the normal flow of the application can be maintained
even after runtime errors.
• In C++, exception is an event or object which is thrown at runtime.
• All exceptions are derived from (std::exception class).
• It is a runtime error which can be handled. If we don't handle the exception, the
program will terminate automatically without any message else, it prints exception
message and terminates the program.

Advantage
• It maintains the normal flow of the application. In such case, rest of the code is executed
even after exception.

To perform exception handling we use following blocks:


• try
• catch, and
• throw
Exception Handling process
Exception Classes
• In C++ standard exceptions are defined in <exception> class that we can
use inside our programs. The arrangement of parent-child class hierarchy
is shown below:
All the exception classes in C++ are derived from std::exception class. Let's
see the list of C++ common exception classes.
Try & Catch Block
• In C++ programming, exception handling is performed using try/catch
statement.
• Try Block: The try block contain statements which may generate
exceptions..
• Throw Block: When an exception occur in try block, it is thrown to the
catch block using throw keyword.
• Catch Block: The catch block defines the action to be taken, when an
exception occur..
• Syntax:
try
{ //code throw parameter;
}
catch(exceptionname ex)
{ //code to handle exception
}
try/catch example
//program for negative number checking…..
#include <iostream>
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;
}
//program for checking number divided by (ZERO)….
#include<iostream>
using namespace std;
int main()
{ int var1=10, var2=0; float var3;
try
{ if(var2!=0)
{ var3=var1/var2;
cout<<"outcome :"<<var3;
}

else
{ throw(var2);
}
}
catch(int exc)
{ cout<<"division by zero is not possible. Please try again with different
value of variables";
}
}
Templates

• A C++ template is a powerful feature added to C++.


• It allows you to define the generic classes and generic
functions and thus provides support for generic programming.
• Generic programming is a technique where generic types are
used as parameters in algorithms so that they can work for a
variety of data types.
Templates can be represented in two ways:
• Function templates
• Class templates
Advantages
• C++ supports a powerful feature known as a template to
implement the concept of generic programming.
• A template allows us to create a family of classes or family of
functions to handle different data types.
• Template classes and functions eliminate the code duplication
of different data types and thus makes the development
easier and faster.
• Multiple parameters can be used in both class and function
template.
• Template functions can also be overloaded.
• We can also use nontype arguments such as built-in or
derived data types as template arguments.
1.Function Template
• A function template works in a similar to a normal function, with one key
difference. A single function template can work with different data types at
a time but, a single normal function can only work with one set of data
types.
• Normally, if you need to perform identical operations on two or more
types of data, you use function overloading to create two functions with
the required function declaration.
• However, a better approach would be to use function templates because
you can perform the same task writing less and maintainable code.
• 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 < class Ttype> ret_type func_name(parameter_list)
{
// body of function.
}
#include <iostream>
using namespace std;

template <typename T>


T max_t(T x, T y)
{
return (x > y)? x: y;
}
int main()
{
cout << max_t<int>(10, 7) << endl; // Call
myMax for int
#include <iostream.h>
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;
cout<<'\n';
a= add(m,n);
cout<<"Addition of m and n is :"<< a;
return 0;
}
• Output: Addition of i and j is : 5 Addition of m and n is : 3.5
2.CLASS 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.
• 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.
#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<long>a2;
a1.add( 10,20);
a2.add(5.5,4.5);
return 0;
}
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;
}

You might also like