OOPS Notes For 3rd Sem ALL Chapters
OOPS Notes For 3rd Sem ALL Chapters
Chapter-1
Concept of Object Oriented Programming
PROCEDURAL ORIENTED PROGRAMMING (pop):-
A program in a procedural language is a list of instruction where each statement tells the
computer to do something. It focuses on procedure (function) & algorithm is needed to
perform the derived computation.
When program become larger, it is divided into function & each function has clearly defined
purpose. Dividing the program into functions & module is one of the cornerstones of
structured programming.
E.g.:- c, basic, FORTRAN.
Characteristics of Procedural oriented programming:-
It focuses on process rather than data.
It takes a problem as a sequence of things to be done such as reading, calculating and
printing. Hence, a number of functions are written to solve a problem.
A program is divided into a number of functions and each function has clearly defined
purpose.
Most of the functions share global data.
Data moves openly around the system from function to function.
Drawback of Procedural oriented programming (structured programming):-
It emphasis on doing things. Data is given a second class status even through data is the
reason for the existence of the program.
Since every function has complete access to the global variables, the new programmer
can corrupt the data accidentally by creating function. Similarly, if new data is to be
added, all the function needed to be modified to access the data.
It is often difficult to design because the components function and data structure do not
model the real world.
For example, in designing graphics user interface, we think what functions, what data
structures are needed rather than which menu, menu item and so on.
It is difficult to create new data types. The ability to create the new data type of its own
is called extensibility. Structured programming languages are not extensible.
To overcome the limitation of Procedural oriented programming languages Object oriented
programming languages were developed.
It refers to the act of representing essential features without including the background
details .Example : For driving , only accelerator, clutch and brake controls need to be learnt
rather than working of engine and other details.
Data Encapsulation:
It means wrapping up data and associated functions into one single unit called class.
A class groups its members into three sections :public, private and protected, where
private and protected members remain hidden from outside world and thereby helps
in implementing data hiding.
Modularity :
The act of partitioning a complex program into simpler fragments called modules is
called as modularity.
It reduces the complexity to some degree and
It creates a number of well-defined boundaries within the program .
Polymorphism:
Poly means many and morphs mean form, so polymorphism means one name multiple
forms.
It is the ability for a message or data to be processed in more than one form.
C++ implements Polymorphism through Function Overloading, Operator overloading
and Virtual functions.
Data hiding & security There is no proper way of Data is hidden in three modes
hiding the data, so data is public, private, and protected.
insecure hence data security increases.
APPLICATION OF OOPs.
1. Client-Server Systems
Object-oriented Client-Server Systems provide the IT infrastructure, creating object-oriented
Client-Server Internet (OCSI) applications. Here, infrastructure refers to operating systems,
networks, and hardware. OSCI consist of three major technologies:
The Client Server
Object Oriented Programming
The Internet
2. Object Oriented Databases
They are also called Object Database Management Systems (ODBMS). These databases store
objects instead of data, such as real numbers and integers. Objects consist of the following:
Attributes: Attributes are data that defines the traits of an object. This data can be as simple
as integers and real numbers. It can also be a reference to a complex object.
Methods: They define the behavior and are also called functions or procedures.
3. Object Oriented Databases
These databases try to maintain a direct correspondence between the real-world and database
objects in order to let the object retain their identity and integrity. They can then be identified
and operated upon.
4. Real-Time System Design
Real time systems inherit complexities that makes difficult to build them. Object-oriented
techniques make it easier to handle those complexities. These techniques present ways of
dealing with these complexities by providing an integrated framework which includes
schedulability analysis and behavioral specifications.
5. Simulation And Modelling System
It’s difficult to model complex systems due to the varying specification of variables. These are
prevalent in medicine and in other areas of natural science, such as ecology, zoology, and
agronomic systems. Simulating complex systems requires modelling and understanding
interactions explicitly. Object-oriented Programming provides an alternative approach for
simplifying these complex modelling systems.
6. Hypertext And Hypermedia
OOP also helps in laying out a framework for Hypertext. Basically, hypertext is similar to
regular text as it can be stored, searched, and edited easily. The only difference is that
hypertext is text with pointers to other text as well.
Hypermedia, on the other hand, is a superset of hypertext. Documents having hypermedia, not
only contain links to other pieces of text and information, but also to numerous other forms of
media, ranging from images to sound.
7. Neural Networking And Parallel Programming
It addresses the problem of prediction and approximation of complex time-varying systems.
Firstly, the entire time-varying process is split into several time intervals or slots. Then, neural
networks are developed in a particular time interval to disperse the load of various networks.
OOP simplifies the entire process by simplifying the approximation and prediction ability of
networks.
8. Office Automation Systems
These include formal as well as informal electronic systems primarily concerned with
information sharing and communication to and from people inside as well as outside the
organization. Some examples are:
Email
Word processing
Web calendars
Desktop publishing
9. CIM/CAD/CAM Systems
OOP can also be used in manufacturing and design applications as it allows people to reduce
the effort involved. For instance, it can be used while designing blueprints, flowcharts, etc.
OOP makes it possible for the designers and engineers to produce these flowcharts and
blueprints accurately.
10. AI Expert Systems
These are computer applications which are developed to solve complex problems pertaining
to a specific domain, which is at a level far beyond the reach of a human brain.
It has the following characteristics:
Reliable
Highly responsive
Understandable
High-performance
Definition - What does C++ Programming Language mean?
C++ is a general-purpose object-oriented programming (OOP) language, developed by Bjarne
Stroustrup, and is an extension of the C language. It is therefore possible to code C++ in a "C
style" or "object-oriented style." In certain scenarios, it can be coded in either way and is thus
an effective example of a hybrid language.
C++ is considered to be an intermediate-level language, as it encapsulates both high- and low-
level language features. Initially, the language was called "C with classes" as it had all the
properties of the C language with an additional concept of "classes." However, it was renamed
C++ in 1983. It is pronounced "see-plus-plus". It is a case sensitive language.
C vs C++
No. C C++
2) Data is less secured in C. In C++, you can use modifiers for class
members to make it inaccessible for
outside users.
5) In C, you can't use functions in structure. In C++, you can use functions in
structure.
7) In C, scanf() and printf() are mainly C++ mainly uses stream cin and cout to
used for input/output. perform input and output operations.
10) C does not provide the feature of C++ supports the feature of namespace.
namespace.
11) Exception handling is not easy in C. It has C++ provides exception handling using
to perform using other functions. Try and Catch block.
C++ Features
C++ is object oriented programming language. It provides a lot of features that are given
below.
1. Simple
2. Machine Independent or Portable
3. Mid-level programming language
4. Structured programming language
5. Rich Library
6. Memory Management
7. Fast Speed
8. Pointers
9. Recursion
10. Extensible
11. Object Oriented
12. Compiler based
1) Simple
C++ is a simple language in the sense that it provides structured approach (to break the
problem into parts), rich set of library functions, data types etc.
2) Machine Independent or Portable
Unlike assembly language, c programs can be executed in many machines with little bit or no
change. But it is not platform-independent.
3) Mid-level programming language
C++ is also used to do low level programming. It is used to develop system applications such as
kernel, driver etc. It also supports the feature of high level language. That is why it is known as
mid-level language.
4) Structured programming language
C++ is a structured programming language in the sense that we can break the program into
parts using functions. So, it is easy to understand and modify.
5) Rich Library
C++ provides a lot of inbuilt functions that makes the development fast.
6) Memory Management
It supports the feature of dynamic memory allocation. In C++ language, we can free the
allocated memory at any time by calling the free() function.
7) Speed
The compilation and execution time of C++ language is fast.
8) Pointer
C++ provides the feature of pointers. We can directly interact with the memory by using the
pointers. We can use pointers for memory, structures, functions, array etc.
9) Recursion
In C++, we can call the function within the function. It provides code reusability for every
function.
10) Extensible
C++ language is extensible because it can easily adopt new features.
11) Object Oriented
C++ is object oriented programming language. OOPs makes development and maintenance
easier where as in Procedure-oriented programming language it is not easy to manage if code
grows as project size grows.
12) Compiler based
C++ is a compiler based programming language, it means without compilation no C++ program
can be executed. First we need to compile our program using compiler and then we can
execute our program.
Basic Structure of C++ Program with Classes:
A C++ program can be developed from a basic structure. The general structure of C++ program
with classes is as shown below (which is also called overview of a C++ program):
1. Documentation Section
2. Preprocessor Directives or Compiler Directives Section
(i) Link Section
(ii) Definition Section
3. Global Declaration Section
4. Class declaration or definition
5. Main C++ program function called main ( )
6. Beginning of the program: Left brace {
(i) Object declaration part;
(ii) Accessing member functions (using dot operator);
7. End of the main program: Right brace}
Chapter-2
OBJECTS & CLASSES
The major components of Object Oriented Programming are Classes & Objects. A Class is a
group of similar objects . Objects share two characteristics: They all have state and
behavior. For example : Dogs have state (name, color, breed, hungry) and behavior (barking,
fetching, wagging tail). Bicycles also have state (current gear, current pedal cadence, current
speed) and behavior (changing gear, applying brakes). Identifying the state and behavior for
realworld
objects is a great way to begin thinking in terms of object-oriented programming. These
real-world observations all translate into the world of object-oriented programming.
Software objects are conceptually similar to real-world objects: they too consist of state and
related behavior. An object stores its state in fields (variables in some programming
languages) and exposes its behavior through functions.
Classes in Programming :
It is a collection of variables, often of different types and its associated functions. Class just
binds data and its associated functions under one unit there by enforcing encapsulation.
Classes define types of data structures and the functions that operate on those data structures.
A class defines a blueprint for a data type.
Declaration/Definition :
A class definition starts with the keyword class followed by the class name; and the class body,
enclosed by a pair of curly braces. A class definition must be followed either by a semicolon or
a list of declarations.
class class_name {
access_specifier_1:
member1;
access_specifier_2:
member2;
...
…
…
} object_names;
Where class_name is a valid identifier for the class, object_names is an optional list of names for
objects of this class. The body of the declaration can contain members that can either be data or
function declarations, and optionally access specifiers.
[Note: the default access specifier is private.
Protected: Class members declared as protected can be used by member functions and
friends (classes or functions) of the class. Additionally, they can be used by classes derived
from the class.
Public: Class members declared as public can be used by any function.
Importance of Access Specifiers
Access control helps prevent you from using objects in ways they were not intended to be
used. Thus it helps in implementing data hiding and data abstraction.
OBJECTS in C++:
Objects represent instances of a class. Objects are basic run time entities in an object oriented
system.
Creating object / defining the object of a class:
The general syntax of defining the object of a class is:-
Class_name object_name;
In C++, a class variable is known as an object. The declaration of an object is similar to that of a
variable of any data type. The members of a class are accessed or referenced using object of a
class.
Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box
Both of the objects Box1 and Box2 will have their own copy of data members.
{
int A, B, Total;
public:
void getdata ()
{ cout< ”\n
enter the value of A
and B”;
cin>>A>>B;
}
void display ()
{
total = A+B;
cout<<”\n the sum of A and B=”<<total;
}
};
Inline function
The functions can be made inline by adding prefix inline to the function definition.
An inline function is a function that is expanded in line when it is invoked.
The complier replaces the function call with the corresponding function code.
Inline function saves time of calling function, saving registers, pushing arguments onto the
stack and returning from function.
We should be careful while using inline function. If function has 1 or 2 lines of code and simple
expressions then only it should be used.
Inline expansion may not work in following situations,
If a loop, a switch or a goto exists in function body.
For function is not returning any value, if a return statement exists.
If function contains static variables.
If function is recursive.
Example:
#include<iostream.h>
{
int c;
c = cube(10);
cout<<c;
return 0;
It makes the program to take up more memory because the statements that define the inline
function are reproduced at each point where the function is called.
Array of objects :
Like array of other user-defined data types, an array of type class can also be created. The
array of type class contains the objects of the class as its individual elements. Thus, an array of
a class type is also known as an array of objects. An array of objects is declared in the same
way as an array of any built-in data type.
The syntax for declaring an array of objects is
class_name array_name [size] ;
}
void books :: putdata ()
{
cout<<"Title:"<<title<< "\n";
cout<<"Price:"<<price<< "\n”;
const int size=3 ;
int main ()
{
books book[size] ;
for(int i=0;i<size;i++)
{
cout<<"Enter details o£ book "<<(i+1)<<"\n";
book[i].getdata();
}
for(int i=0;i<size;i++)
{
cout<<"\nBook "<<(i+l)<<"\n";
book[i].putdata() ;
}
return 0;
}
In this example, an array book of the type class books and size three is declared. This implies
that book is an array of three objects of the class books. Note that every object in the array
book can access public members of the class in the same way as any other object, that is, by
using the dot operator. For example, the statement book [i] . getdata () invokes the getdata ()
function for the ith element of array book.
When an array of objects is declared, the memory is allocated in the same way as to
multidimensional arrays. For example, for the array book, a separate copy of title and price is
created for each member book[0], book[l] and book[2]. However, member functions are
stored at a different place in memory and shared among all the array members. For instance,
the memory space is allocated to the the array of objects book of the class books,
Friend Function:- A friend function is not a member function ,has full access rights to the
private members of the class.
Syntax :-
class ABC
{
------------
------------
public:
--------------
--------------
friend void xyz(void);
}
Characteristics of friend function:
· It is not in the scope of the class to which it has been declared as friend.
· Since it is not in the scope of the class ,it cannot be called using the object of that
class.
· It can be invoked like a normal function without the help of any object.
· Unlike member functions ,it cannot access the member names directly and has to use
an object name and dot membership operator with each member name .
· It can be declared either in the public or the private part of a class without affecting
its meaning.
Uaually ,it has the objects as arguments.
Example:-
#include<iostream.h>
#include<conio.h>
Class sample
{
int a;
int b;
public:
void setvalue()
{
a=25;
b=40;
}
friend float mean(sample s);
};
float mean (sample s)
{
return float (s.a+s.b)/2;
}
void main()
{ sample x;
x.setvalue();
cout<<mean(x);
}
// A function friendly to two classes
#include<iostream.h>
class XYZ
{
int x;
public:
void setvalue(int i)
{
x=I;
}
friend void max(XYZ,ABC);
};
class ABC
{
int a;
public:
void setvalue(int i)
{
a=i;
}
friend void max(XYZ,ABC);
};
void max(XYZ m, ABC n)
{
if (m.x>=n.a)
cout<<m.x;
else
cout<<n.x;
}
void main()
{
ABC abc;
abc.setvalue(10);
XYZ xyz;
xyz.setvalue(20);
max(xyz,abc);
}
On the other hand, the memory space for the member functions is allocated only once when
the class is defined. In other words, there is only a single copy of each member function, which
is shared among all the objects. For instance, the three objects, namely, book1, book2 and
book3 of the class book have individual copies of the data members title and price. However,
there is only one copy of the member functions getdata () and putdata () that is shared by all
the three objects
#include <iostream.h>
void Add(int num1, int num2)\\ Function 1: Receives 2 integer parameters
{
cout<<num1 + num2 <<endl;
}
void Add(float num1, float num2)\\Function 2: Receives 2 float parameters.
{
cout<<num1 + num2 <<endl;
}
void Add(int num1, int num2, int num3)\\Function 3: Receives 3 int parameters
{
cout<<num1 + num2 + num3 <<endl;
}
int main()
{
float a=10.5,b=20.5;
Add(10,20); \\ Calls function 1
Add(a,b); \\ Calls function 2
class Box {
public:
static int objectCount;
// Constructor definition
Box(double l = 2.0, double b = 2.0, double h = 2.0) {
cout <<"Constructor called." << endl;
length = l;
breadth = b;
height = h;
private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
int main(void) {
Box Box1(3.3, 1.2, 1.5); // Declare box1
Box Box2(8.5, 6.0, 2.0); // Declare box2
return 0;
}
When the above code is compiled and executed, it produces the following result −
Constructor called.
Constructor called.
Total objects: 2
class Box {
public:
static int objectCount;
// Constructor definition
Box(double l = 2.0, double b = 2.0, double h = 2.0) {
cout <<"Constructor called." << endl;
length = l;
breadth = b;
height = h;
private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
int Box::objectCount = 0;
int main(void) {
// Print total number of objects before creating object.
cout << "Inital Stage Count: " << Box::getCount() << endl;
return 0;
}
When the above code is compiled and executed, it produces the following result −
Inital Stage Count: 0
Constructor called.
Constructor called.
Final Stage Count: 2
Chapter-3
Constructor in C++
Constructor is a special method which is invoked automatically at the time of object creation. It is used
to initialize the data members of new object generally. A constructor is a special member function
which is used to initialize the object of a class.
Note:-
A constructor is distinct from other member functions because its name is same as the name of
the class. It is executed automatically when an object is declared .The only restriction that applies
to constructor is that it must not have a return type not even void.
Constructor of a class is the first member function to be executed automatically when an object of
the class is created.
{
Bank B;
}
When an object B is created ,constructor will be called automatically and it will initialize the
data members x and y=0.
Example:-
#include<iostream.h>
#include<conio.h>
class fibonacci
{
private:
int fo,f1,fib;
public:
fibonacci();
void increment();
void display();
};
fibonacci::fibonacci()
{
fo=0;
f1=1;
fib=fo+f1;
}
void fibonacci::increment()
{
fo=f1;
f1=fib;
fib=fo+f1;
}
void fibonacci:: display()
{
cout<< fib<<“\t”;
}
void main()
{
clrscr();
fibonacci F;
for(int i=0;i<=15;++i)
{
F.display();
F.increment();
getch();
}
}
1. Default Constructors: Default constructor is the constructor which doesn’t take any argument.
It . has no parameters.
#include <iostream.h>
class construct {
public:
int a, b;
// Default Constructor
construct()
{
a = 10;
b = 20;
}
};
int main()
{
// Default constructor called automatically
// when the object is created
construct c;
cout << "a: " << c.a << endl
<< "b: " << c.b;
return 1;
}
Output:
a: 10
b: 20
Note: Even if we do not define any constructor explicitly, the compiler will automatically provide a
default constructor implicitly.
2. Parameterized constructor:- The constructor that can take arguments are called
Parameterized constructor. It is possible to pass arguments to constructors. Typically, these
arguments help initialize an object when it is created. To create a parameterized constructor,
simply add parameters to it the way you would to any other function. When you define the
constructor’s body, use the parameters to initialize the object.
Example:
class Bank
{
private:
int x,y;
public:
Bank(int a, int b)
-----------------------
-------------------
};
Bank:: Bank(int a, int b)
{
x=a;
y=b;
}
In the parameterized constructor we pass the initial values as arguments to the constructor in two
ways: i) Implicit call ii) Explicit call
Implicit call: Bank b1(5,11); Explicit Call: Bank B1=Bank(5,11);
Example:-
#include<iostream.h>
#include<conio.h>
class Bank
{
int x,y;
public:
Bank(int ,int);
void putdata()
{
cout<<x<<“\n”<<y;
}
};
Bank :: Bank(int a,int b);
{
x=a;
y=b;
}
void main()
{
clrscr();
Bank B1(5,11);
Bank B2=Bank(6,34);
cout<<“ object 1”;
B1.putdata();
cout<<“object 2”;
B2.putdata();
getch();
}
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.
3. Copy Constructor:- A copy constructor is a member function which initializes an object using
another object of the same class. In other word, a copy constructor takes a reference to its own
class as parameter i.e. a constructor having a reference to an instance of its own class as an
argument is known as copy constructor.
A copy constructor has the following general syntax:
ClassName (ClassName &old_obj);
In C++, a Copy Constructor may be called in following cases:
1. When an object of the class is returned by value.
2. When an object of the class is passed (to a function) by value as an argument.
3. When an object is constructed based on another object of the same class.
4. When the compiler generates a temporary object.
Example:
#include<iostream.h>
class sample
{
int x;
public:
sample()
{
x=0;
}
sample(int a)
{
x=a;
}
sample (sample & S)
{
x=s.x
}
void display(void)
{
cout<<x;
}
};
void main()
{
clrscr();
Sample P(45);
Sample Q(P);
Sample R=P;
Sample T;
T=P;
cout<<“ \n value of p:”;
P.display();
cout<<“\n value of Q:”;
Q.display();
cout<<“ \n value of R”;
R.display();
cout<<“\nValue of T:”;
T.display();
getch();
}
rollno = x;
name = str;
}
};
int main()
{
// student A initialized with roll no 10 and name None
Student A(10);
C++ Destructors
C++ destructor is a special member function that is executed automatically when an object is
destroyed that has been created by the constructor. C++ destructors are used to de-allocate the
memory that has been allocated for the object by the constructor. In other words a destructor is also a
member function whose name is the same as the class name but is preceded by tilde (‘~’)
A destructor takes no arguments and no return types can be specified for it. It is called automatically
by the compiler when an object is destroyed. A destructor cleans up the storage ( memory area of the
object) that is no longer accessible.
Need for Destructors
Allocated resources (like constructor) must be de-allocated before the object is destroyed. It works as
a de-allocating and releasing memory area and it perform our works as a clean up tasks. Therefore,
a destructor is equally useful as a constructor is.
Its syntax is same as constructor except the fact that it is preceded by the tilde sign.
~class_name() { }; //syntax of destructor
class stud
{
stud() //constructor
{
cout << “ welcome” 20
}
~stud() //destructor
{
}
};
stud s1;
Note:- Object Are Destroyed In The Reverse Order Of Creation. So destructor is invoked in the
reverse order of constructor.
Example:-
#include<iostream.h>
#include<conio.h>
class sample
{
public:
sample( )
{
cout<<“ object is born\n”;
}
~sample ()
{
cout <<“ object is dead”
}
};
void main()
{
clrscr();
sample S;
cout<<“ Main terminated “<<endl;
getch();
}
Chapter-4
Inheritance in C++
One of the most important concepts in object-oriented programming is that of inheritance.
Inheritance allows us to define a class in terms of another class, which makes it easier to create and
maintain an application. This also provides an opportunity to reuse the code functionality and fast
implementation time.
When creating a class, instead of writing completely new data members and member functions, the
programmer can designate that the new class should inherit the members of an existing class. This
existing class is called the base class, and the new class is referred to as the derived class.
The idea of inheritance implements the is a relationship. For example, mammal IS-A animal, dog IS-A
mammal hence dog IS-A animal as well and so on.
In C++, inheritance is a process in which one object acquires all the properties and behaviors of its
parent object automatically. In such way, you 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.
You can clearly see that above process results in duplication of same code 3 times. This increases the
chances of error and data
redundancy. To avoid this
type of situation, inheritance
is used. If we create a class
Vehicle and write these three
functions in it and inherit the
rest of the classes from the
vehicle class, then we can
simply avoid the duplication of data
and increase re-usability. Look at the
below diagram in which the three
classes are inherited from vehicle
class:
Using inheritance, we have to write
the functions only one time instead of
three times as we have inherited rest
of the three classes from base
class(Vehicle).
Implementing inheritance in C++: For creating a sub-class which is inherited from the base class we
have to follow the below syntax.
Syntax:
class subclass_name : access_mode base_class_name
{
//body of subclass
};
Here, subclass_name is the name of the sub class, access_mode is the mode in which you want to
inherit this sub class for example: public, private etc. and base_class_name is the name of the base
class from which you want to inherit the sub class.
Note: A derived class doesn’t inherit access to private data members. However, it does inherit a full
parent object, which contains any private members which that class declares. In C++, the default mode
of visibility is private. The private members of the base class are never inherited.
Modes of Inheritance
1. Public mode: If we derive a sub class from a public base class. Then the public member of the
base class will become public in the derived class and protected members of the base class will
become protected in derived class.
2. Protected mode: If we derive a sub class from a Protected base class. Then both public member
and protected members of the base class will become protected in derived class.
3. Private mode: If we derive a sub class from a Private base class. Then both public member and
protected members of the base class will become Private in derived class.
Note : The private members in the base class cannot be directly accessed in the derived class, while
protected members can be directly accessed. For example, Classes B, C and D all contain the variables
x, y and z in below example. It is just question of access.
class B : public A
{
// x is public
// y is protected
// z is not accessible from B
};
class C : protected A
{
// x is protected
// y is protected
// z is not accessible from C
};
Types Of Inheritance
C++ supports five types of inheritance:
Single inheritance
Multiple inheritance
Hierarchical inheritance
Multilevel inheritance
Hybrid 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.
Example.
#include <iostream>
using namespace std;
class A
{
int a = 4;
int b = 5;
public:
int mul()
{
int c = a*b;
return c;
}
};
class B : private A
{
public:
void display()
{
int result = mul();
std::cout <<"Multiplication of a and b is : "<<result<< std::endl;
}
};
int main()
{
B b;
b.display();
return 0;
}
Output:
Multiplication of a and b is : 20
In the above example, class A is privately inherited. Therefore, the mul() function of class 'A' cannot be
accessed by the object of class B. It can only be accessed by the member function of class B.
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>
using namespace std;
class Animal {
public:
void eat() {
cout<<"Eating..."<<endl;
}
};
class Dog: public Animal
{
public:
void bark(){
cout<<"Barking..."<<endl;
}
};
class BabyDog: public Dog
{
public:
void weep() {
cout<<"Weeping...";
}
};
int main(void) {
BabyDog d1;
d1.eat();
d1.bark();
d1.weep();
return 0;
}
Output:
Eating...
Barking...
Weeping...
#include <iostream>
using namespace std;
class A
{
protected:
int a;
public:
void get_a(int n)
{
a = n;
}
};
class B
{
protected:
int b;
public:
void get_b(int n)
{
b = n;
}
};
return 0;
}
Output:
The value of a is : 10
The value of b is : 20
Addition of a and b is : 30
In the above example, class 'C' inherits two base classes 'A' and 'B' in a public mode.
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.
}
#include <iostream>
Output:
2
5
Area of the triangle is : 5
#include <iostream>
using namespace std;
class A
{
protected:
int a;
public:
void get_a()
{
std::cout << "Enter the value of 'a' : " << std::endl;
cin>>a;
}
};
class B : public A
{
protected:
int b;
public:
void get_b()
{
std::cout << "Enter the value of 'b' : " << std::endl;
cin>>b;
}
};
class C
{
protected:
int c;
public:
void get_c()
{
std::cout << "Enter the value of c is : " << std::endl;
cin>>c;
}
};
void mul()
{
get_a();
get_b();
get_c();
std::cout << "Multiplication of a,b,c is : " <<a*b*c<< std::endl;
}
};
int main()
{
D d;
d.mul();
return 0;
}
Output:
class A {
public:
void show()
{
cout << "Hello form A \n";
}
};
class B : public A {
};
class C : public A {
};
int main()
{
D object;
object.show();
}
Compile Errors:
prog.cpp: In function 'int main()':
prog.cpp:29:9: error: request for member 'show' is ambiguous
object.show();
^
prog.cpp:8:8: note: candidates are: void A::show()
void show()
^
prog.cpp:8:8: note: void A::show()
How to resolve this issue?
To resolve this ambiguity when class A is inherited in both class B and class C, it is declared as virtual
base class by placing a keyword virtual as :
Syntax for Virtual Base Classes:
Syntax 1:
class B : virtual public A
{
};
Syntax 2:
class C : public virtual A
{
};
Note: virtual can be written before or after the public. Now only one copy of data/function member
will be copied to class C and class B and class A becomes the virtual base class.
Virtual base classes offer a way to save space and avoid ambiguities in class hierarchies that use
multiple inheritances. When a base class is specified as a virtual base, it can act as an indirect base
more than once without duplication of its data members. A single copy of its data members is shared
by all the base classes that use virtual base.
Example 1
#include <iostream>
class A {
public:
int a;
A() // constructor
{
a = 10;
}
};
int main()
{
D object; // object creation of class d
cout << "a = " << object.a << endl;
return 0;
}
Output:
a = 10
Explanation :The class A has just one data member a which is public. This class is virtually inherited
in class B and class C. Now class B and class C becomes virtual base class and no duplication of data
member a is done.
Example 2:
#include <iostream>
class A {
public:
void show()
{
cout << "Hello from A \n";
}
};
int main()
{
D object;
object.show();
}
Output:
Hello from A
/* Other members */
};
A complete example:
A pure virtual function is implemented by classes which are derived from a Abstract class. Following is
a simple example to demonstrate the same.
#include<iostream>
class Base
{
int x;
public:
virtual void fun() = 0;
int getX() { return x; }
};
int main(void)
{
Derived d;
d.fun();
return 0;
}
Output:
fun() called
int main(void)
{
Test t;
return 0;
}
Output:
Compiler Error: cannot declare variable 't' to be of abstract
type 'Test' because the following virtual functions are pure
within 'Test': note: virtual void Test::show()
2) We can have pointers and references of abstract class type.
For example the following program works fine.
#include<iostream>
class Base
{
public:
virtual void show() = 0;
};
int main(void)
{
Base *bp = new Derived();
bp->show();
return 0;
}
Output:
In Derived
3) If we do not override the pure virtual function in derived class, then derived class also becomes
abstract class.
The following example demonstrates the same.
#include<iostream>
class Base
{
public:
int main(void)
{
Derived d;
return 0;
}
Compiler Error: cannot declare variable 'd' to be of abstract type
'Derived' because the following virtual functions are pure within
'Derived': virtual void Base::show()
4) An abstract class can have constructors.
For example, the following program compiles and runs fine.
#include<iostream>
// An abstract class with constructor
class Base
{
protected:
int x;
public:
virtual void fun() = 0;
Base(int i) { x = i; }
};
int main(void)
{
Derived d(4, 5);
d.fun();
return 0;
}
Output:
x = 4, y = 5
int x;
int main()
{
}
Output:
Eating bread...
Chapter-5
Polymorphism
The term "Polymorphism" is the combination of "poly" + "morphs" which means many forms. It is a
greek word. 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 the same time can have different characteristic. Like
a man at the same time is a father, a husband, an employee. So the same person posses different
behaviour in different situations. This is called polymorphism.
Polymorphism is considered as one of the important features of Object Oriented Programming.
In the above case, the prototype of display() function is the same in both the base and derived class.
Therefore, the static binding cannot be applied. It would be great if the appropriate function is
selected at the run time. This is known as run time polymorphism.
Run time polymorphism: Run time polymorphism is achieved when the object's method is
invoked at the run time instead of compile time. It is achieved by method overriding which is also
known as dynamic binding or late binding.
The function to be invoked is known at the The function to be invoked is known at the
compile time. run time.
It is also known as overloading, early binding and It is also known as overriding, Dynamic
static binding. binding and late binding.
It is less flexible as mainly all the things execute at It is more flexible as all the things execute
the compile time. at the run time.
#include <iostream.h>
void Add(int num1, int num2)\\ Function 1: Receives 2 integer parameters
{
cout<<num1 + num2 <<endl;
}
void Add(float num1, float num2)\\Function 2: Receives 2 float parameters.
{
cout<<num1 + num2 <<endl;
}
void Add(int num1, int num2, int num3)\\Function 3: Receives 3 int parameters
{
cout<<num1 + num2 + num3 <<endl;
}
int main()
{
float a=10.5,b=20.5;
Add(10,20); \\ Calls function 1
Add(a,b); \\ Calls function 2
Add(1,2,3); \\ Calls function 3
return 0;
}
Type conversion
Let's see a simple example.
#include<iostream.h>
void fun(int);
void fun(float);
void fun(int i)
{
std::cout << "Value of i is : " <<i<< std::endl;
}
void fun(float j)
{
std::cout << "Value of j is : " <<j<< std::endl;
}
int main()
{
fun(12);
fun(1.2);
return 0;
}
The above example shows an error "call of overloaded 'fun(double)' is ambiguous". The fun(10)
will call the first function. The fun(1.2) calls the second function according to our prediction. But, this
does not refer to any function as in C++, all the floating point constants are treated as double not as a
float. If we replace float to double, the program works. Therefore, this is a type conversion from float
to double.
o Function with Default Arguments
Let's see a simple example.
#include<iostream.h>
void fun(int);
void fun(int,int);
void fun(int i)
{
std::cout << "Value of i is : " <<i<< std::endl;
}
void fun(int a,int b=9)
{
std::cout << "Value of a is : " <<a<< std::endl;
std::cout << "Value of b is : " <<b<< std::endl;
}
int main()
{
fun(12);
return 0;
}
The above example shows an error "call of overloaded 'fun(int)' is ambiguous". The fun(int a, int b=9)
can be called in two ways: first is by calling the function with one argument, i.e., fun(12) and another
way is calling the function with two arguments, i.e., fun(4,5). The fun(int i) function is invoked with
one argument. Therefore, the compiler could not be able to select among fun(int i) and fun(int a,int
b=9).
o Function with pass by reference
Let's see a simple example.
#include <iostream.h>
void fun(int);
void fun(int &);
int main()
{
int a=10;
fun(a); // error, which f()?
return 0;
}
void fun(int x)
{
std::cout << "Value of x is : " <<x<< std::endl;
}
void fun(int &b)
{
std::cout << "Value of b is : " <<b<< std::endl;
}
The above example shows an error "call of overloaded 'fun(int&)' is ambiguous". The first function
takes one integer argument and the second function takes a reference parameter as an argument. In
this case, the compiler does not know which function is needed by the user as there is no syntactical
difference between the fun(int) and fun(int &).
Operators Overloading
Operator overloading is a compile-time polymorphism in which the operator is overloaded to provide
the special meaning to the user-defined data type. Operator overloading is used to overload or
redefines most of the operators available in C++. It is used to perform the operation on the user-
defined data type. For example, C++ provides the ability to add the variables of the user-defined data
type that is applied to the built-in data types.
The advantage of Operators overloading is to perform different operations on the same operand.
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 two operands. So a single operator ‘+’ when placed
between integer operands , adds them and when placed between string operands, concatenates them.
Operator that cannot be overloaded are as follows:
Scope operator (::)
Sizeof
member selector(.)
member pointer selector(*)
ternary operator(?:)
Syntax of Operator Overloading
return_type class_name : : operator op(argument_list)
{
// body of the function.
}
Where the return type is the type of value returned by the function.
class_name is the name of the class.
operator op is an operator function where op is the operator being overloaded, and the operator is
the keyword.
Rules for Operator Overloading
Existing operators can only be overloaded, but the new operators cannot be overloaded.
The overloaded operator contains atleast one operand of the user-defined data type.
We cannot use friend function to overload certain operators. However, the member function can
be used to overload those operators.
When unary operators are overloaded through a member function take no explicit arguments, but,
if they are overloaded by a friend function, takes one argument.
When binary operators are overloaded through a member function takes one explicit argument,
and if they are overloaded through a friend function takes two explicit arguments.
int x;
public:
A(){}
A(int i)
{
x=i;
}
void operator+(A);
void display();
};
void A :: operator+(A a)
{
int m = x+a.x;
cout<<"The result of the addition of two objects is : "<<m;
}
int main()
{
A a1(5);
A a2(4);
a1+a2;
return 0;
}
Output:
The result of the addition of two objects is : 9
Function Overriding
If derived class defines same function as defined in its base class, it is known as function overriding in
C++. It is used to achieve runtime polymorphism. It enables you to provide specific implementation of
the function which is already provided by its base class.
C++ Function Overriding Example
Let's see a simple example of Function overriding in C++. In this example, we are overriding the eat()
function.
#include <iostream.h>
class Animal {
public:
void eat(){
cout<<"Eating...";
}
};
class Dog: public Animal
{
public:
void eat()
{
cout<<"Eating bread...";
}
};
int main(void) {
Dog d = Dog();
d.eat();
return 0;
}
Output:
Eating bread...
Output:
Value of x is : 5
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.
C++ virtual function Example
Let's see the simple example of C++ virtual function used to invoked the derived class in a program.
#include <iostream.h>
class A {
public:
virtual void display()
{
cout << "Base class is invoked"<<endl;
}
};
class B:public A
{
public:
void display()
{
cout << "Derived Class is invoked"<<endl;
}
};
int main()
{
A* a; //pointer of base class
B b; //object of derived class
a = &b;
a->display(); //Late Binding occurs
}
Output:
Derived Class is invoked
{
public:
void show()
{
std::cout << "Derived class is derived from the base class." << std::endl;
}
};
int main()
{
Base *bptr;
//Base b;
Derived d;
bptr = &d;
bptr->show();
return 0;
}
Output:
Derived class is derived from the base class.
In the above example, the base class contains the pure virtual function. Therefore, the base class is an
abstract base class. We cannot create the object of the base class.
Chapter-6
I/O Operations and File Processing in C++
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.
C/C++ IO are based on streams, which are sequence of bytes flowing in and out of the programs (just
like water and oil flowing through a pipe). In input operations, data bytes flow from an input
source (such as keyboard, file, network or another program) into the program. In output operations,
data bytes flow from the program to an output sink (such as console, file, network or another
program). Streams acts as an intermediaries between the programs and the actual IO devices, in such
the way that frees the programmers from handling the actual devices, so as to archive device
independent IO operations.
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.
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.
Formatted & Unformatted I/O Operations
C++ provides both the formatted and unformatted IO functions. In formatted or high-level IO, bytes are
grouped and converted to types such as int, double, string or user-defined types. In unformatted or
low-level IO, bytes are treated as raw bytes and unconverted. Formatted IO operations are supported
via overloading the stream insertion (<<) and stream extraction (>>) operators.
Unformatted data
The printed data with default setting by the I/O function of the language is known as unformatted
data.
It is the basic form of input/output and transfers the internal binary representation of the data
directly between memory and the file.
For example, in cin statement it asks for a number while executing. If the user enters a decimal
number, the entered number is displayed using cout statement. There is no need to apply any
external setting, by default the I/O function represents the number in decimal format.
Formatted data
If the user needs to display a number in hexadecimal format, the data is represented with the
manipulators are known as formatted data.
It converts the internal binary representation of the data to ASCII characters which are written to
the output file.
It reads characters from the input file and coverts them to internal form.
For example, cout<<hex<<13; converts decimal 13 to hexadecimal d. Formatting is a
representation of data with different settings (like number format, field width, decimal points etc.)
as per the requirement of the user.
Managing output with Manipulators
Formatted output is very important in development field for easily read and understand. Manipulators
are helper functions that make it possible to control input/output streams using operator << or
operator >>.
C++ offers the several input/output manipulators for formatting, commonly used manipulators
are given below...
Manipulator Declaration in
endl iostream.h
setw iomanip.h
setprecision iomanip.h
setf iomanip.h
endl
endl manipulator is used to Terminate a line and flushes the buffer.
Difference b/w '\n' and endl
When writing output in C++,you can use either std::endl or '\n' to produce a newline, but each has a
different effect.
std::endl sends a newline character '\n' and flushes the output buffer.
'\n' sends the newline character, but does not flush the output buffer.
The distinction is very important if you're writing debugging messages that you really need to see
immediately, you should always use std::endl rather than '\n' to force the flush to take place
immediately.
The following is an example of how to use both versions, although you cannot see the flushing
occurring in this example.
#include <iostream.h>
int main()
{
cout<<"USING '\\n' ...\n";
cout<<"Line 1 \nLine 2 \nLine 3 \n";
cout<<"USING end ..."<< endl;
cout<< "Line 1" << endl << "Line 2" << endl << "Line 3" << endl;
return 0;
}
Output
USING '\n' ...
Line 1
Line 2
Line 3
USING end ...
Line 1
Line 2
Line 3
C++ file handling provides a mechanism to store output of a program in a file and read from a file on
the disk. So far, we have been using <iostream> header file which provide functions cin and cout to
take input from console and write output to a console respectively. Now, we introduce one more
header file <fstream> which provides data types or classes ( ifstream , ofstream , fstream ) to read
from a file and write to a file.
Datatype Description
ofstream Used for creating a file and write data on files.
ifstream Used for reading the data from files.
fstream Used for both read and write data from files.
fstream.h:
This header file includes the definitions for the stream classes ifstream, ofstream and fstream. In C++
file input output facilities implemented through fstream.h header file. It contain predefines set of
operation for handling file related input and output, fstream class ties a file to the program for input
and output operation.
Opening a File
A file can be opened using:
By the constructor method. This will use default streams for file input or output. This method
is preferred when file is opened in input or output mode only.
Example : ofstream file(“student.dat”); or ifstream file(“student.dat”);
By the open() member function of the stream. It will prefer when file is opened in various
modes i.e ios::in, ios::out, ios::app, ios::ate etc.
e.g fstream file;
file.open(“book.dat”, ios::in | ios::out | ios::binary);
The open() function is used to open multiple files which uses the same stream object.
The fstream or ofstream object is used to open a file for writing and ifstream object is used to
open a file for reading.
Syntax:
void open(const char *filename, ios::openmode mode);
where,
ios::nocreate If file does not exist this file mode ensures that no file is created and open() fails.
ios::noreplace If file does not exist, a new file gets created but if the file already exists, the open()
fails.
All these above modes can be combined using the bitwise operator (|). for example, ios::out | ios::app |
ios::binary
eof(): This function determines the end-of-file by returning true(non-zero) for end of file otherwise
returning false(zero).
Closing a File
The close() function is used for closing a file.
When a program terminates, it automatically closes or flushes all the streams, releases all the
allocated memory and closes all the opened files. But a good practice for programmer to close all
the opened files before the program termination.
Syntax:
Stream_object.close(); e.g file.close();
A file must be closed after completion of all operation related to a file.
Writing to a File
The insertion operator (<<) is used to write information in a file.
The ofstream or fstream object is used instead of cout object.
Reading from a File
The extraction operator (>>) is used to read information from a file into your program.
The ifstream or fstream object is used instead of cin object.
Input and Output Operation
Following functions are used for I/O Operation:
Function Description
Function Description
#include <fstream.h>
#include <iostream.h>
int main ()
{
char name[50];
cout << name << endl; // write the data at the screen.
return 0;
}
Output:
Writing to the file
Enter your name:
EASY TECH CLASSES
If argc is greater than zero,the array elements from argv[0] to argv[argc-1] will contain pointers
to strings.
Argv[0] is the name of the program , After that till argv[argc-1] every element is command -line
arguments.
Properties of Command Line Arguments:
1. They are passed to main() function.
2. They are parameters/arguments supplied to the program when it is invoked.
3. They are used to control program from outside instead of hard coding those values inside the
code.
4. argv[argc] is a NULL pointer.
5. argv[0] holds the name of the program.
6. argv[1] points to the first command line argument and argv[n] points last argument.
Note : You pass all the command line arguments separated by a space, but if argument itself has a
space then you can pass such arguments by putting them inside double quotes “” or single quotes ”.
// C program to illustrate
// command line arguments
#include<stdio.h>
Practice programs:-
Chapter-5
Exception Handling
What is Exception?
Exception is a problem that occurs during the execution of a program. It is a response to
exceptional circumstances like runtime errors while a program is running. In other word ,
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, it prints exception message and terminates the program.
What is 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.
An exception transfers the control to special functions called Handlers.
Exception handling makes it easy to separate the error handling code.
It provides a way to transfer control from one part of a program to another.
Exception handling makes code readable and maintainable. It separates the code to the normal flow.
Function can handle or specify any exceptions they choose.
Advantage
It maintains the normal flow of the application. In such case, rest of the code is executed even after
exception.
C++ 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.
Exception Description
Following are the three specialized keywords where exception handling is built.
1. throw
2. try
3. catch
1. throw
Using throw statement, an exception can be thrown anywhere within a code block. It is used to list the
exceptions that a function throws, but doesn't handle itself.
Following example shows throwing an exception when dividing by zero condition occurs.
float div(int x, int y)
{
if(y==0)
{
throw ”Divide by zero condition!!!”;
}
return (x/y);
}
2. try
Try represents a block of code that can throw an exception. It identifies a block of code which
particular exceptions will be activated. Try block followed by one or more catch blocks.
Syntax:
try
{
//Code
}
catch(ExceptionName e1)
{
//Catch block
}
catch(ExceptionName e2)
{
//Catch block
}
catch (ExceptionName e3)
{
//Catch block
}
3. Catch
Catch represents a block of code executed when a particular exception is thrown. It follows the try
block which catches any exception.
Syntax:
try
{
//code
}
catch(ExceptionName e)
{
//code to handle exception
}
Output:
Before Try Block
Inside Try Block
Exception Caught
Executed After Catch Exception
C++ User-Defined Exceptions
The new exception can be defined by overriding and inheriting exception class functionality.
You can define your own exceptions. Following example shows how to implement your own
exception.
Output:
MyException caught
New Exception
In the above program, test() is a public method provided by exception class. It returns the cause
of an exception.
{
MyHandler();
}
catch(const char*)
{
cout <<”Caught exception inside Main\n”;
}
cout << “Main end”;
return 0;
}
Output :
Main start
Caught exception inside MyHandler
Caught exception inside Main
Main end
- Thus, exception rethrown by the catch block inside MyHandler() is caught inside main();