C++ with oops
C++ with oops
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
v) Easier to update/fix the program by replacing individual At times, instead of dealing with individual objects, it is
modules rather than large amounts of code. convenient to talk collectively about a group of similar objects
where all the objects of this group will have the same set of
2.2 Disadvantages of Structured Programming
attributes and methods.
i) Lack of encapsulation.
In the object-oriented programming paradigm, this collection of
ii) Same code repetition. objects corresponding to a particular group is known as a
class. All programs under this paradigm contain a description
iii) Lack of information hiding. of the structure (attributes) and behavior (methods). In a
iv) Change of even a single data structure in a program program, various objects are created from these classes. The
necessitates changes at many places throughout it, and process of creation of an object from a class is called
hence, the changes become very difficult to track even in a ‘instantiation’ and the object created is known as an instance
reasonably sized program. of the class. Every object created will have s ‘state’ associated
with the description of the structure in the class from which it
v) Not much reusability of code. has been instantiated. The state of an object is defined by the
set of values assigned to its corresponding attributes of the
object.
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
8) The OOP supports polymorphism of operations. ignores the remainder of the information. There are different
levels of abstraction.
9) The concepts of OOP have got integrated with most of the
prominent object-oriented methodologies of software If we take example of a class ‘student’, the class may have
development in a better way and help in reducing the plenty of attributes like, name, roll number, father’s name,
development effort and time as compared with that of date of birth, class, year or semester, course, marks obtained,
structured methodologies based on structured address for correspondence etc. The list can be very long. But,
programming. when we use this ‘student’ class in some program, not many of
these attribute would be required to be used. Only those
5. OBJECT-ORIENTED PROGRAMMING CONCEPTS attributes which are of interest i.e. the attributes that are
required to define the state of the program at any point of time
The Object-Oriented Programming is based on principles and during the execution of the program shall be included in the
provides the developers of various object-oriented programming definition of the class and rest of these attributes shall never
languages with a variety of new concepts to be incorporated in be used and hence be not included in the program. Same is
those languages. Some of the commonly found important true for behavior depicted by the methods of the class
concepts in most of the OOP languages are as: ‘student’.
Objects are the basic run time entities in an object-oriented Information or data hiding in an object is characterized by its
system. They may represent a person, a place, a bank account, knowledge of a design decision which it hides from all other
a table of data or any item that the program has to handle. objects. The interface of an object is chosen to reveal only the
They may also represent user-defined data such as vectors, desired data or working of the object. It is the process of hiding
time and lists. Programming problem is analyzed in term of all details of an object that do not contribute to its essential
objects and the nature of communication between them. characteristics; typically, the structure of an object as well as
Program objects should be chosen such that they match the implementation of its methods is hidden from other
closely with the real-world objects. Objects take up space in objects. There can be two types of information hiding:
the memory and have an associated address like a record in functional information hiding related to the hiding of
Pascal, or a structure in c. implementation details of methods (behavioral information of a
particular object) and data hiding (structural information of a
When a program is executed, the objects interact by sending particular object). C++ allows varying degree of visibility of
messages to one another. For example, if “customer” and objects like public, private and protected. So the mechanism of
“account” are to object in a program, then the customer object information hiding is said to provide a strictly controlled access
may send a message to the count object requesting for the to the information enclosed within the capsule.
bank balance. Each object contain data, and code to
manipulate data. Objects can interact without having to know 5.5 Encapsulation
details of each other’s data or code. It is a sufficient to know
the type of message accepted, and the type of response The wrapping up of data and function into a single unit (called
returned by the objects. class) is known as encapsulation. Data and encapsulation is
the most striking feature of a class. The data is not accessible
5.2 Classes to the outside world, and only those functions which are
wrapped in the class can access it.
Objects contain data and code to manipulate that data. The
entire set of data and code of an object can be made a user- Encapsulation as consisting of separating the external aspects
defined data type with the help of class. In fact, objects are of an object which are accessible to other objects, from the
variables of the type class. Once a class has been defined, we internal implementation details of the object, which are hidden
can create any number of objects belonging to that class. Each from other objects. It is also known as information hiding and
object is associated with the data of type class with which they it prevents clients from seeing the object’s inside view, where
are created. A class is thus a collection of objects similar types. the behavior of the abstraction is implemented. In reference to
classes and objects in OOP, encapsulation is the process of
A class is a collection of similar entities which have same enclosing within these classes and objects the attributes and
structure and exhibit same behavior. These are used to the methods. It is the programmers who specify what
describe something in the real world like places, organization, information in an object can be shared with other objects.
roles, things, occurrences etc. A class is said to describe the Information hiding cannot be treated as encapsulation, both
structure and behavior of these sets of similar entities called are related but altogether different aspects e.g. an array or a
objects. As opposed to actual objects, the class gives a general record structure also encloses the information but this
description of these objects like a template, blueprint or a information cannot be said to be hidden. It is true that the
pattern; and contains the definitions of all the attributes and encapsulation mechanism like classes and objects hide
methods which will become the part of each object created information but these also provide visibility of some of their
form the class. Only after a class has been defined, specific information through well defined interfaces.
instances of the class can be created and these instances as
objects of the class is called instantiation. 5.6 Polymorphism
5.3 Data Abstraction Polymorphism or the ability to appear in many forms, is one of
the vital primary characteristic concepts of OOP. ‘Poly’ means
Abstraction is a technique which allows the hiding or ‘many’ and ‘morph’ means ‘form’. In reference to OOP, it is an
elimination of the irrelevant; and focusing on the essential. ability of assigning different meanings to entities such as
Abstraction is defined as a view of a problem that extracts the variable, methods or objects so that these can be made to
essential information relevant to a particular purpose and exhibit more than one form. It provides the programmers with
the flexibility of processing any object differently depending
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
upon their data types. Using this concept, a programmer can Types of Inheritance
redefine various methods of the classes derived from their base
classes. Objects of different types can receive the same i) Single level Inheritance
message and respond in different ways provided these objects
have the same method definition (i.e. interface). The calling A derived class with only one base class is called single
object, also sometimes known as the client, need not know inheritance.
what type of object it is calling, the only thing that it needs to
know or ensure is that the called object has a method of a ii) Multi level Inheritance
specific name with defined arguments. Polymorphism is more
often than not applied to derived classes, where the methods of A derived class with one base class and that base class is a
the parent class are replaced with those having different derived class of another is called multilevel inheritance.
behaviors.
iii) Multiple Inheritance
There are two types of polymorphism:
A derived class with multiple base class is called multiple
i) Static or compile-time polymorphism inheritance.
In static polymorphism, which form of the method (from among iv) Hierarchical inheritance
the various available forms) is to be called and executed is
Multiple derived classes with same base class is
decided during the time of compilation, the example being
called hierarchical inheritance.
‘Method Overloading’. In method overloading, same method
name having different parameters is used more than once in
v) Hybrid inheritance
the same class. Which method is to be called and executed
depends upon the parameters passes by the calling method
Combination of multiple and hierarchical inheritance is
and is decided during the compilation of the program.
called hybrid inheritance.
ii) Dynamic or run time polymorphism
5.8 Message Passing
The dynamic polymorphism is applied in the form of method
In object oriented languages, you can consider a running
overriding which means there can exist two or more methods
program under execution as a pool of objects where objects are
in a program which have the same signature (name; return
created for ‘interaction’ and later destroyed when their job is
type; type, number and order of arguments to be passed)
over. This interaction is based on ‘messages’ which are sent
having different implementations.
from one object to another asking the recipient object to apply
one of its own methods on itself and hence, forcing a change in
5.7 Inheritance
its state. The objects are made to communicate or interact with
each other with the help of a mechanism called message
Inheritance is the process by which objects of one class
passing. The methods of any object may communicate with
acquired the properties of objects of another classes.
each other by sending and receiving messages in order to
Inheritance is a mechanism by which the classes inherit the
change the state of the object. An Object may communicate
attributes and methods of some other class. Inheritance is a
with other objects by sending and receiving messages to and
way to reuse the code of some existing or already defined
from their methods in order to change either its own state or
classes. The classes, in this case, are said to have ‘a-kind-of’
the state of other objects taking part in this communication or
and ‘is-a’ relationship with the other classes. Using this
that of both. An object can both send and receive messages.
property of OOP, one class can extend other classes by
including additional methods or attributes. The original class
The messages are sent and received by passing various
is called the ‘super class’ of the extending class and the
variables among specific methods using the signatures of the
extended class is called the ‘subclass’ of the class that is being
methods. Every method has a well defined and structured
extended. The subclass is sometimes known with the name of
signature. The signature of a method is composed of:
‘derived’ class and the super class with the name of ‘base’
class. The derived or subclasses classes can further be used to
a) a type, associated with the variable whose value after
have their own derived subclasses. This kind of a relationship
execution of the method, would be returned to the object that
of classes through inheritance gives rise to an inheritance
would invoke the method;
hierarchy of the classes.
b) the types of a specific number of variables and the order
As a example, if you take ‘car’ as a super class; then you can
associated with these variables whose values would be passed
treat SUV, sedan, sports car as its subclasses. All or some of
to the method before execution of the method starts. All these
these subclass cars have some common attributes (structure)
variables have a well defined format and corresponding values
and methods (behaviour). But the structure and behaviour of
at any instant of time available for communication during the
these subclass cars is not restricted to those of the superclass
execution of the program.
‘car’. A subclass car can contain methods and attributes in
addition to those inherited from the superclass ‘car’ e.g. a
5.9 Dynamic Binding
sports car will generally have only two doors whereas a sedan
will have four. The subclasses can also contain methods that Binding refers to the linking of a procedure call to the code to
override the methods they have inherited to have unique be executed in response to the call. Dynamic binding means
implementation of these methods. Various categories of that the code associated with a given procedure call is not
inheritance which are often used in OOP are single level, multi- known until the time of the call at run time. It is associated
level, multiple inheritance etc. with polymorphism and inheritance. A function call associated
with a polymorphic reference depends on the dynamic type of
that reference.
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
6. BENEFITS OF OOP • AI and expert systems
By now, you might have understood the basic concepts of • Neural networks and parallel programming
object-oriented programming. Therefore you are in a better
position to appreciate the following as some of the major • Decision support and office automation systems
benefits of OOP :
• CIM/CAM/CAD systems
1) As OOP is closer to the real world phenomena, hence, it is
easier to map real world problems onto a solution in OOP.
7. Application of OOP
• Real-time system
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
1. CLASS 1.2 Encapsulation
Class is an object template. Every object under that class has Encapsulation is one of the important characteristics of
the same data format, definition and responds in the same Object-Oriented Programming Language. A class can be
manner to an operation.A class is a user defined data type like described as a collection of data members and member
any other built-in data type for example int, char. It is most functions. This property of C++ which allow wrapping up of
important feature of C++. It makes C++ an Object-Oriented data and functions into a single unit is called encapsulation.
language. Data encapsulation is most striking feature of a class. The
advantages of encapsulation are data hiding, information
1.1 Defining a Class hiding and implementation independence.
A class has a class name, a set of attributes (data If the implementation details are not known to the user, it is
members/characteristics) and a set of actions or services called information hiding. Restrictions of external access to
(function members/methods). The common syntax of a class features of a class results in data hiding. The user’s interface is
declaration is given as follows: not affected by changing the implementation mechanism. A
change in the implementation is done easily without affecting
class Class_name the interface. This leads to implementation independence.
{
private: 1.3 Accessibility Rules/Labels
variable declaration;
In class declaration, we have used three terms private, public
function declaration;
and protected. Private, public and protected are known as
public:
visibility labels, used to control the access to members (data
variable declaration;
members and member functions) of a class.
function declaration;
protected: As we know that purpose of data encapsulation is to prevent
variable declaration; accidental modification of information of a class. Data can be
function declaration; protected from external tempering by users and access to
}; specific methods can also be controlled. However, an entire
program cannot be hidden. A part of the program needs to be
A class is defined by the keyword class. The class specifies the accessed by users. For this and many other reasons, we need
type and scope of variables and functions declared inside the to access the members of a class in controlled way. It is
class. The variables (data) declared inside the class are known achieved by imposing a set of rules- the manner in which a
as data members and the functions (methods) are known as class is to be manipulated and data and functions of the class
member functions. Being the part of the class, data and can be accessed. The set of rules is known as accessibility
function are called members of the class. The body of the class rules. This accessibility rules are achieved by using three
is enclosed within braces and terminated by the colon. The keywords private, public and protected. These keywords are
keywords private, public and protected are known as visibility called access-control specifiers (visibility mode). The visibility of
labels, which defines the visibility of members. Data Members class members is explained in following Table:
are declared as private and Data member functions are declared
Visibility of class members
as public.
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
protected: Thus, an object is an instantiation of a class. The common
int y; syntax of instantiating object of a class/declaration of a object
void fun2( ) is as follows:
{
class className objectName1, objectName2 …;
//This function can also refer to data members x, y, z and
or
functions fun1( ), fun2( ) and fun3( )
className objectName1, objectName2 …;
}
public : We can see that the declaration of an object is similar to that of
int z; any basic type.We can also notice that keyword class is
void fun3( ) optional.
{ Objects can also be created by placing their names
//This function can also refer to data members x, y, z and immediately after the closing brace. Which have following
functions fun1( ), fun2( ) and fun3( ) syntax:
} class class_name
}; {
.
Now, consider the statements
.
A obja; .
int b; } objname1,objname2,…;
The above statements define an object obja and an integer We can assess the member of a class using the member assess
variable b. The accessibility of members of the class A is operator, dot(.). The syntax for assessing data member of a
illustrated through the obja as follows: class is given as follows :
b=obja.y;
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
small then it should be defined inside the class, otherwise it By default, all member functions defined inside the class are
should be defined outside the class. inline functions. The member function defined outside the
class can be made inline by prefixing the keyword inline to
If function is defined outside the class, its prototype
function
declaration must be done inside the class. While defining the
function, scope access operator and class name should inline return type class name :: function name
precede the function name. The following program illustrates (signature)
everything about member functions and how to access private
member of the class. The inline is a keyword and acts as function qualifier. The
return type is functions return type i.e., the function returns
3.1 Member Function inside the Class values of this type. The class name is the name of class that
Member function inside the class can be declared in public or the function belongs to. Scope access operator separates class
private section.The syntax for specifying a member function name and function name. Signature means argument list
declaration inside the class is similar to a normal function passed function.
definition . when a function is defined inside a class it is
treated as inline function so only small functions are defined 4. STATIC MEMBER VARIABLES AND FUNCTIONS
inside the class.
4.1 Static Member Variables
3.2 Member Function Outside the Class We know that each object has its separate set of data member
variables in memory. The member functions are created only
Member functions that are declared inside a class have to be
once and all objects share the functions. No separate copy of
defined outside the class. Their definition is very much like the
function of each object is created in the memory like data
normal function. There should be a mechanism of binding the
member variables.
functions to the class to which the belong. This it done by
scope resolution operator (::). It acts as an identity label. This
It is possible to create common member variables like function
label tells the complier which class the functions belongs to. using the static keyword. Once a data member variable is
declared as static, only one copy of that member is created for
To define a function outside the class the following care must
the whole class. The static is a keyword used to preserve value
be taken:
of a variable. When a variable is declared as static it is
(1) The prototype of function must be declared inside the initialized to zero. A static functions or data element is only
class. recognized inside the scope of the present class.
(2) The function name must be preceded by class name and If a local variable is declared with static keyword, it preserves
its return type separated by scope access operator as the last value of the variable. A static data item is helpful when
follows: all the objects of the class share a common data. The static
data variable is accessible within the class, but its value
return_typeclass_name::function_name(argument list) remains in the memory throughout the whole program.
{
The class and scope of the static member variable is defined
function body
outside the class. The reasons are :
}
(1) The static data members are associated with the class and
3.3. CHARACTERISTICS OF MEMBER FUNCTIONS not with any object.
(1) The difference between member and normal function is (2) The static data members are stored individually rather than
that the former function can be invoked freely where as an element of an object.
the latter function only by using an object of the same
(3) The static data member variable must be initialized
class.
otherwise the linker will generate an error.
(2) The same function can be used in any number of classes.
(4) The memory for static data is allocated only once.
This is possible because the scope of the function is
limited to their classes and cannot overlap one another. (5) Only one copy of static member variable is created for the
whole class for any number of objects. All the objects have
(3) The private data or private function can be accessed by
common static data member.
public member function. Other function have no access
permission.
Syntax of defining static data member
(4) The member function can invoke one another without
using any object or dot operator. Class class_name
{
3.4. OUTSIDE MEMBER FUNCTION INLINE …..
static data_type data member;
It is a good practice to declare function prototype inside the …..
class and definition outside the class. The inline mechanism …..
reduces overhead relating to accessing the member function. It };
provides better efficiency and allows quick execution of data_typeclass_name :: data member=intial value;
functions. An inline member function is similar to macros. Call
to inline function in the program, puts the function code in the class Student
caller program. This is known as inline expansion. Inline {
functions are also called as open subroutines because their static int a;
code is replaced at the place of function call in the caller public:
function. The normal functions are known as closed void count()
subroutines because when such functions are called, the {
control passes to the function.
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
c++; have an access to the private data of a class. If we want
} to operate a function on objects of two different class
void getdata() then it is not possible. In such situations C++ provides
{
the friend function which is used to access the private
cout<<"a= "<<a<<endl;
}
members of a class. Friend function is not a member of
}; any class. So it is defined without scope resolution
int Student::a= 0; operator. Syntax of declaring friend function is:
voidmain ()
{
Student:getdata(); class class_name
Student::count(); {
Student::getdata(); …
public:
} friend return_typefunction_name(arguments);
….
};
4.2 Static Member Functions
Like member variables, functions can also be declared as Friend function have following properties:
static. When a function is defined as static, it can access only
(i) A friend function is not in the scope of the class to
static member variables and functions of the same class. The which it has been declared as friend.
non-static members are not available to these functions. The
(ii) A friend function cannot be called using the object
static member function declared in public section can be
invoked using its class name without using its objects. The
of that class. It can be invoked like a normal
static keyword makes the function free from the individual function without the use of any object.
(iii) Unlike member functions, it can not access the
object of the class and its scope is global in the class without
creating any side effect for other part of the program. The members directly. However, it can use the object
programmer must follow the following points while declaring and dot membership operator with each member
static function : name to access both private and public members.
(1) Just one copy of static member is created in the memory (iv) It can be declared either in public or private part of
for entire class. All objects of the class share the same a class without affecting its meaning.
copy of static member. (v) It has got objects as arguments.
(2) Static member functions can access only static data
members or functions. class student
{
(3) Static member functions can be invoked using class name.
int id,roll;
(4) It is also possible to invoke static member functions using public:
objects. void setdata(int i,int r)
(5) When one of the objects changes the value of data member {
variables, the effect is visible to all the objects of the class. id=i; roll=r;
}
friend void showdata(student);
Static member function can also be declared in private section. };
The private static function must be invoked using static public
function.
void showdata(student s)
The static public member variable can also be initialized in {
function main ( ) like other variables. The static member cout<<”id=”<<s.id;
variable using class name and scope access operator can be cout<<”roll=”<<s.roll;
accessed. The scope access operator is also used when }
variables of same name are declared in global and local scope.
void main()
4.3 Static Object
{
In C, it is common to declare variable static that gets initialized student s;
to zero. The object is a composition of one or more member s.setdata(100,200);
variables. There is a mechanism called constructor to initialize showdata(s);
member variables of the object to desired values. The keyword }
static can be used to initialize all class data member variables
to zero. Declaring object itself as static can do this Thus, all its
associated members get initialized to zero.
5. FRIEND Keyword
5.1 FRIEND Function 5.2 Friend class
Private members cannot be accessed from outside the It is possible to declare entire class as a friend class. When all
class. It implies that a non member function cannot the functions need to access another class in such a situation,
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
we can declare an entire class as friend class. The friend is not
transferable or inheritable from one class to another. Declaring
class, A to be a friend of class B does not mean that class B is
also a friend of class A i.e. friendship in not exchangeable. The
friend class are applicable when we want to make available
private data of a class to another class.
class A
{
int a=10;
public:
friend class B;
};
class B
{
public:
void showdata(A obj)
{
cout<<obj.a<<endl;
}
};
int main()
{
Aobj1;
B obj2;
Obj2.showdata(obj1);
}
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
Operator Overloading (v) Unary operators declared as member functions take no
arguments; if declared as global functions, they take one
The mechanism which provides special meaning to operators
argument.
is called operator overloading. The operator overloading
feature of C++ is one of the methods of realizing (vi) Binary operators declared as member functions take one
polymorphism.Operator overloading enables us to make the argument; if declared as global functions, they take two
standard operators, like +, -, * etc, to work with the objects arguments.
of our own data types. So what we do is, write a function
(vii) If an operator can be used as either a unary or a binary
which redefines a particular operator so that it performs a
operator (&, *, +, and - ), we can overload each use separately.
specific operation when it is used with the object of a class.
Operator overloading is very exciting feature of C++. The (viii) Overloaded operators cannot have default arguments.
concept of operator overloading can also be applied to data
conversion. It enhances the power of extensibility of C++. (ix) All overloaded operators except assignment (operator=) are
Thus operator overloading concepts are applied to the inherited by derived classes.
following two principle areas: (x) The first argument for member-function overloaded operators
Extending capability of operators to operate on user defined is always of the class type of the object for which the operator is
data, and invoked (the class in which the operator is declared, or a class
derived from that class). No conversions are supplied for the
Data conversion first argument.
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
Syntax
class complex
{
Defining an overloaded operator is like defining a function, but
int real, imaginary;
the name of that function is operator #, in which # represents public:
the operator that‘s being overloaded. The number of arguments complex()
in the overloaded operator‘s argument list depends on two {
}
factors: complex(int a, int b)
{
1. Whether it‘s a unary operator (one argument) or a binary real = a;
operator (two arguments). imaginary = b;
}
2. Whether the operator is defined as a global function (one
void operator-();
argument for unary, two for binary) or a member function (zero
void display()
arguments for unary, one for binary – the object becomes the {
left-hand argument). cout<<”Real value”<<real<<endl;
cout<<”imaginary value”<<imaginary<<endl;
}
};
void complex::operator-()
Return_type class_name :: operator op (op_argument_list) {
{ real = -real;
Body of function imaginary = -imaginary;
}
}
void main()
{
complex c1(10,12);
cout<<”real and img value before operation<<endl;
Following lines define the steps in overloading the operators c1.display();
c1; //c1- /*It will give error*/
a. Build a class that defines the data type that is going to use in cout<<”real and imag value after operation”<<endl;
operation of overloading. c1.display();
}
b. Declare the operator function operator op() in public area of
class.
class complex
Invoking Operator Function {
int real;
(i) For member Function int imaginary;
public:
a. For unary operator: op m or m op complex() //default constructor
b. For binary operator: m op n or m.operator op (n) {
}
(ii) For friend Function complex(int a, int b)
{
a. For unary operator: operator op (m) real = a;
imaginary = b;
b. For binary operator: operator op (m, n) }
friend void operator -();
void display()
Overloading unary operators {
cout<<‖real value is‖<<real<<endl;
To declare a unary operator function as a non static member, cout <<‖imaginary value is:‖<<imaginary<<endl;
you must declare it in the form: }
};
return_typeoperator op();
friend void complex :: operator - (complex &c)
where op is one of the operators listed in the preceding table. To {
declare a unary operator function as a global function, you c.real = - c.real;
must declare it in the form: c.imaginary = - c.imaginary;
}
return_typeoperatorop( arg); void main()
{
Where op is described for member operator functions and the complex c1(50,100);
argis an argument of class type on which to operate. An cout<<”real &imag value before”<<endl;
overloaded unary operator may return any type. c1.diaplay(); //calling operator overloading fun
-c1; //c1-; It will give you an error.
cout<<”real & imagvalue after operator”<<endl;
c1.display();
}
class complex
{
int real, imaginary;
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
public: whether they appear before (prefix) or after (postfix) the
complex() object they‘re acting upon. When the compiler sees, for
{ example, ++a (a pre-increment), it generates a call to
} operator ++(a); but when it sees a++, it generates a call to
complex(int a,int b) operator ++(a, int.) That is, the compiler differentiates
{ between the two forms by making calls to different
real = a; overloaded functions.
imaginary = b;
} class Inc
void operator +(complex c); {
}; int count ;
void complex::operator+(complex c) public:
{ Inc()
complex temp; {
temp.real = real + c.real; count = 0 ;
temp.imaginary = imaginary + c.imaginary; }
cout<<”real sum is”<<temp.real<<endl; Inc(int C)
} {
void main() count = C ;
{ }
complex c1(10,20); Inc operator ++ ()
complex c2(20,30); {
c1+c2; return Inc(++count);
} }
Inc operator -- ()
{
Binary Operator Overloading using friend function return Inc(--count);
}
class complex void display()
{ {
int real; cout<< count <<endl ;
int imaginary; }
public: };
complex(){ } //default constructor void main()
complex(int a, int b) {
{ Inc a, b(10), c, d, e(5), f(10);
real = a; cout<< "Before using the operator ++()\n";
imaginary = b; cout<< "a = ";
} a.display();
friend complex operator +(complex c1, complex c2); cout<< "b = ";
void display() b.display();
{ ++a;
cout<<”real value is”<<real<<endl; b++;
cout<<”imaginary value is:”<<imaginary<<endl; cout<< "After using the operator ++()\n";
} cout<< "a = ";
}; a.display();
complex operator + (complex c1, complex c2) cout<< "b = ";
{ b.display();
complex tmp; c = ++a;
tmp.real = c1.real + c2.real d = b++;
tmp.imaginary = c1.imaginary + c2.imaginary; cout<< "Result prefix (on a) and postfix (on b)\n";
return(tmp); cout<< "c = ";
} c.display();
void main() cout<< "d = ";
{ d.display();
complex c1(10,20),c2(3,4),c3(); cout<< "Before using the operator --()\n";
c3 = c1 + c2; cout<< "e = ";
c3.display(); e.display();
} cout<< "f = ";
f.display();
--e;
f--;
cout<< "After using the operator --()\n";
cout<< "e = ";
e.display();
cout<< "f = ";
Unary Operators (Increment and decrement) f.display();
}
The overloaded ++ and – – operators present a dilemma because
we want to be able to call different functions depending on
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
Overloading assignment operator ('=' ) int real,img;
public:
class Complex void get(int real,intimg)
{ {
this->real=real;
private:
this->img=img;
double real, imag; }
public: friend ostream& operator<<(ostream&,A);
Complex() friend istream& operator>>(istream&,A&);
{ void show()
real = 0; {
imag = 0; cout<<real<<"+"<<img<<"i"<<endl;
}
}
Complex(double r, double i) };
{
real = r; ostream& operator<<(ostream&out,Aobj)
imag = i; {
} out<<"real: "<<obj.real<<" img:"<<obj.img;
return out;
double getReal() const
}
{
return real; istream& operator>>(istream&in,A&obj)
} {
double getImag() const in>>obj.real>>obj.img;
{ return in;
return imag; }
int main()
}
{
Complex & operator=(const Complex &); A a;
}; cout<<"enter real and img value of complex no:"<<endl;
Complex &Complex::operator=(const Complex& c) cin>>a;
{ cout<<"complex no is:"<<endl;
real = c.real; cout<<a;
imag = c.imag;
}
return *this;
}
int main()
{
Complex c1(5,10);
Complex c2(50,100);
cout<< "c1= " << c1.getReal() << "+" << c1.getImag() << "i" ;
cout<< "c2= " << c2.getReal() << "+" << c2.getImag() << "i";
c2 = c1;
cout<< "c2= " << c2.getReal() << "+" << c2.getImag() << "i";
class A
{
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
Virtual functions };
Virtual functions should be define in the public section of a
In polymorphism, a single function or an operator functioning class to realize its full potential benefits. When such a
in many ways depends upon the usage to function properly. declaration is made, it allows to decide which function to be
In order for this to occur, the following conditions must used at runtime, based on the type of object, pointed to by
apply: the base pointer rather than the type of the pointer.
1. All different classes must be derived from a single base Need of Virtual Function
class
we do have a list of pointer to objects of a super class in an
2. The member function must be declared virtual in the base inheritance hierarchy and we wish to invoke the functions of
class. its derived classes with the help of single list of pointers
provided that the functions in super class and sub classes
The form of a member function can be changed at runtime. have the same name and signature. That in turn means we
Such member functions are called virtual functions and the want to achieve run time polymorphism.
corresponding class is called polymorphic class. The objects
of the polymorphic class, addressed by pointers, change at Pointers to derived types
runtime and respond differently for the same message. The
word „virtual‟ means something that does not exist in We know that pointer of one type may not point to an object
reality, some sort of imaginary thing. The concept of virtual of another type. we shall now learn about the one exception
function is the same as a function, but it does not really to this general rule: a pointer to an object of a base class can
exist although it appears in needed places in a program. also point to any object derived from that base class.
The object-oriented programming language C++ implements Similarly, a reference to a base class can also reference any
the concept of virtual function as a simple member object derived from the original base class. In other words, a
function, like all member functions of the class. The base class reference parameter can receive an object of types
functionality of virtual functions can be overridden in its derived from the base class, as well as objects within the
derived classes. base class itself.
Function Overriding
To cause late binding to occur for a particular function, C++ Rules for Virtual Functions
requires that we use the virtual keyword when declaring
the function in the base class. Late binding occurs only The virtual functions must be the members of some class.
with virtual functions, and only when we‟re using an
A class member function can be declared to be virtual by
address of the base class where those virtual functions
just specifying the keyword „virtual‟ in front of the function
exist, although they may also be defined in an earlier base
declaration.
class. To create a member function as virtual, we simply
precede the declaration of the function with the keyword
Virtual Functions enables derived (sub) class to provide its
virtual. Only the declaration needs the virtual keyword,
own implementation for the function already defined in its
not the definition. If a function is declared as virtual in the
base (super) class.
base class, it is virtual in all the derived classes. The
redefinition of a virtual function in a derived class is
Virtual Functions give power to the derived class functions
usually called function overriding. All derived-class
to override the function in its base class with the same name
functions that match the signature of the base-class
and signature.
declaration will be called using the virtual mechanism.
wecan use the virtual keyword in the derived-class Virtual Functions can‟t be static members.
declarations, but it is redundant and can be confusing.
Only the functions that are members of some class can be
Properties of Virtual Functions declared as virtual that means we can‟tdeclare regular
functions or friend functions as virtual.
Virtual functions are member functions of a class.
A virtual function can be a friend of another class.
Virtual functions are declared with the keyword virtual.
A virtual function in a base class must be defined, even
Virtual function takes a different functionality in the derived
though it may not be used.
class.
If one will call the virtual function with the pointer having
Definition of Virtual Functions
the reference to the base class object then the function of
the base class will be called for sure.
The general syntax to declare a virtual function uses the
following format
The corresponding functions in the derived class must
agree with the virtual function‟s name and signature that
class class_name
means both must have same name and signature.
{
public:
virtual return_typemember_function_name(arguments)
{
...
... Limitations of Virtual Functions
}
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
The function call takes slightly longer due to the virtual Syntax of pure virtual function
mechanism, and it also makes it more difficult for the
compiler to optimize because it doesn't know exactly which The syntax of declaring a pure virtual function is as follows:
function is going to be called at compile time. virtual <return type><function name><(argument list)> =0;
Virtual functions will usually not be inlined. A class member function can be declared to be pure
virtual by just specifying the keyword „virtual‟ in front and
Size of object increases due to virtual pointer. putting „=0‟ at the end of the function declaration.
Pure Virtual Functions are the specific type of virtual Abstract Classes
functions. A virtual function with no function body is called
pure virtual function i.e. a pure virtual function is a function Abstract classes act as a container of general concepts from
declared in a base class that has no definition relative to which more specific classes can be inherited. Thus an
base class. A pure virtual function purely exists in base abstract class is one that is not used to create any object of
class only to be overridden by the derived class functions. A its own but it solely exists to act as a base class for the other
base class only specifies that there is a function with this classes that means the abstract class must be a part of
name and signature which will be implemented by any of some inheritance hierarchy. An abstract class can further be
derived class or by some other derived class in the same illuminated through following points:
inheritance hierarchy. Such classes are also called abstract
base class. An abstract class can not be instantiated that means
abstract classes can not have their own instances but their
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
child or derived classes may have their own instances
provided the child class itself is not an abstract class.
class Shape
{
protected:
float l;
public:
void getData()
{
cin>> l;
}
voidmain()
{
Square s;
Circle c;
cout<< "Enter length to calculate the area of a square: ";
s.getData();
cout<<"Are of square: " <<s.calculateArea();
cout<<"\nEnter radius to calculate the area of a circle: ";
c.getData();
cout<< "Area of circle: " <<c.calculateArea();
}
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
EXCEPTION HANDLING Example
int main()
The term exception itself implies an unusual condition. {
Exceptions are anomalies that may occur during execution of int a,b;
a program. Exceptions are not errors but they still cause the cout<<"Enter value of a and b:";
program to misbehave. They are unusual conditions which are cin>>a>>b;
generally not expected by the programmer to occur. An try
exception in this sense is an indication of a problem that {
occurs during a programs‟s execution. TheException if(b==0)
Handling typical exceptions may include conditions like divide throw 0;
by zero, access to an array outside its range, running out of cout<<"division is:"<<a/b;
memory etc. }
catch(int x)
The exception handling mechanism C++ deals with exceptions {
by performing following tasks: cout<<"division not possible:";
a. Identify the problem }
b. Inform that an exception has occurred return 0;
c. Exception handler catches the exception information }
d. Exception handler takes corrective actions
These tasks are incorporated in C++ exception handling Multiple catch Block:
mechanism in two segments, one to detect (try) and inform
(throw) about the exception, and the other to catch the It is also possible that a program may have more than one
exception and take appropriate actions to handle it. As exception condition. In such cases multiple catch statements
indicated earlier, the C++ exception handling mechanism is are needed to handle the different types of exceptions. Now
built upon following three expressions: when an exception is thrown, the exception handlers are
Try searched in order for an appropriate match. The first handler
Throw that matches the thrown exception object type is executed.
Catch Rest of the catch blocks are then skipped and the control goes
to first statement following the last catch block. This indicates
The expression try is used to preface (enclose in braces) that that in case of multiple catch blocks matching the thrown
block which may generate exceptions. This block is often exception, only the first matching catch block is executed.
termed as try block. The throw expression is invoked when an
exception is detected. It informs the catch block that an
exception has occurred. The exception handling code is
enclosed in catch block. The catch block catches the void test(int x)
exception thrown by the throw expression and handles it in a {
predefined manner. try
{
The keyword „try‟ is used to enclose the statements that may if (x==1) throw x;
generate an exception. These statements begin with a try else
keyword and are enclosed in braces. When the try block if (x==0) throw “x‟;
encounters an exception, it uses the throw keyword to pass else
the information to the exception handling block. The exception if(x==-1) throw 1.0;
handling block is enclosed within a block preceding the catch }
keyword. This catch block should immediately follow the try catch (char c)
block that throws the exception. The general syntax of these {
statements and blocks is as follows: cout<< “caught a character \n”;
}
catch(int m)
try {
{ cout<< “caught an integer \n”;
……………… }
……………… catch(double d)
throwexception; {
………………. cout<< “caught a double \n”;
………………. }
} }
catch (type arg) int main()
{ {
……………….. cout<< “x==1 \n”;
……………….. test(1);
} cout<< “x==0 \n”;
test(0);
cout<< “x==-1 \n”;
test(-1);
cout<< “x==2 \n”;
test(2);
}
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
Catch all exceptions
catch(…)
{
……
……
}
Example:
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
TEMPLATE void show ()
{
Templates are one of the most prominent examples of reuse cout<< x << “and” << y << “\n”;
concept in action. It supports the idea of generic programming }
by providing facility for defining generic classes and functions. };
Thus a template class provides a broad architecture which can int main()
be used to create a number of new classes. Similarly, a template {
function can be used to write various versions of the function. Example <float, int> test1 (3.45, 345);
Example <int, char> test2 (100, “m”);
CLASS TEMPLATE test1.show();
test2.show();
A template may be considered as a kind of macro. When the }
actual object of that type is to be defined, the template definition
is substituted with required data type. For example, if we define
a template Array of elements, then this same generic definition FUNCTION TEMPLATE
may be used to create Array of integers or of characters or float
quantities. We need not make a new class definition every time. Function templates are similar to class templates in the sense
We define a generic class with a parameter that s replaced by a that they create a genericfunction type. This generic function
particular data type at the time of actual use of that class. This can then be used to create a family of functionsthat may take
is the reason template classes are also known as parameterized different arguments. A function template can be defined as
classes. Designing a template class thus involves a simple follows:
process of creating a generic class with an anonymous type. The template <class T>
general syntax for defining a class template is: return_typefunction_name (arguments of type T)
{
template <class T> ………..
class classname ……….
{ body of function with argument of type T
……….. ………..
………. }
class specification with anonymous type T
……….. Function templates are another way of handling overloaded
}; function requirement. Ifoverloaded functions perform identical
operations for different type of data then theycan be more
This class definition is similar to an ordinary appropriately and conveniently declared as function templates.
classdefinition exceptthat of the use of template<class
T> and use of type T inside the class definition. The Example:
template<class T> tells the compiler that it is template <class X>
atemplate class with parameter Tinstead of a normal X big(X a,X b)
class definition. The declaration thus creates a {
parameterized classwith T as the parameter, which if(a>b)
can be substituted with any valid data type. This can return a;
be done by a statement of the following form: else
return b;
classname<type>objectname(argument list); }
int main()
A class template can also be created by using multiple generic {
data types as arguments. The general syntax for such definition cout<<big(2,3)<<endl;
would be as below: cout<<big(3.4,5.4)<<endl;
}
template <class T1, class T2, …….>
class classname A template function may also be overloaded in a manner similar
{ ……….. ………. to other functions. Infact, function templates and overloading
class specification with anonymous type T are intimately related. All the functiontemplatespecializations
……….. generated from a function template have the same name, so
}; the compiler uses overloading resolution to invoke the proper
Example function. A functiontemplate can be overloaded in several ways:
a) functions having same name but different parameters
template<class T1, class T2> b) providing a non-template functions with the same function
class Example name but differentarguments
{
T1 x; Whenever, the compiler has to perform the matching process to
T2 y; determine whatfunction to call, it achieves the overloading
Public: resolution as follows:
Example(T1 a, T2 b) a) call an ordinary function that has an exact match
{ b) call a template function that could be created with an exact
x = a; match
y = b; c) try normal overloading resolution to ordinary functions and
} call the one thatmatches.
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
In case no match is found, the compiler generates an error. In FILE HANDLING
case there are multiplematches for the function call, the
compiler considers the call to be ambiguous and thecompiler Many real world applications require reading and writing large
generates an error message. It would also be worth mentioning number of data items. Usually large volumes of data are
that noautomatic conversions are applied to arguments on the stored as files on disk. Like many high level programming
template functions. languages, C++ also provides mechanism to read and write
data items from files. A C++ program can thus take input from
#include <iostream> a disk file and also write data to it. C++ file handling
#include <iomanip> mechanism is quite similar to console input-output
#include <cmath> operations. It uses streams (called file streams) as an interface
template<class T> between programs and files.
void roots(T a, T b, T c)
{ The stream that supplies data to the program is called input
T d = b*b - 4*a*c; stream and the one receiving data from program for writing to
if (d==0) file is called output stream.
{
cout<< “R1 = R2 =” << -b/(2*a) <<endl;
}
else if (d > 0)
{
cout<< “Roots are real \n”;
float R = sqrt (d);
float R1 = (-b + R) / (2*a);
float R2 = (-b - R) / (2*a);
cout<< “R1 =” << R1 << “and” ;
cout<< “R2 =” << R2 <<endl;
}
else
{
cout<< “Roots are complex \n”; The Figure shows a C++ program that reads data from one file
float R1 = -b /(2*a); and writes the output to another file. The input stream is
float R2 = sqrt (-d) / (2*a); connected to data file used for input and output stream is
cout<< “Real part =” << R1 <<endl; connected to results file used for output. Programs can do
cout<< “Imaginary part =” <<R2 <<endl; reading and writing on the same file as well.
}
} The I/O system of C++ contains a set of classes that provide
int main() methods for reading and writing from files. These classes
{ are ifstream, ofstream and fstream. All these classes are
cout<< “Integer coefficients \n”; derived from fstream base class and also inherits features
roots (1, -5, 6); from iostream class. The stream classes and their
cout<< “\n Float coefficients \n”; inheritance shown as
roots (1.5, 3.6, 5.0);
};
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
The ofstreamclass provides functions for output operations Example 1
and include functions like put(), write() etc.
#include<fstream>
The fstreamclass provides support for simultaneous input and #include<iostream>
output operations. It also inherits all functions from using namespace std;
istreamand ostreamclasses through iostream. int main()
{
The filebufis used for setting the file buffers for read and write ofstreamfout;
operations. This is required since volume of data is read fout.open("hello.dat");
and written to files. fout<<"hello c++";
fout.close();
Opening and Closing Files return 0;
}
Every disk file has a name .To read data from a file or to write
data into it, we first need to open the file. This opened file
has to be then connected to input-output stream so that
the corresponding program becomes able read and write
from it. A file stream can be defined using any of the three Example 2
classes ifstream, ofstream or fstream, depending upon the
purpose of the file. A file can be opened either by using the #include<fstream>
constructor function of the class or by invoking member #include<iostream>
function open () of the class. In order to open file using using namespace std;
constructor function, we may use statements of the form:
int main()
ifstreaminfile (“data”); {
ifstream fin;
ofstreamoutfile (“results”); fin.open("hello.dat");
char ch;
A file can also be opened using open (). The general syntax of
ch=fin.get(); //fin>>ch
open () is as follows:
while(!fin.eof())
stream-object.open(“filename”);
{
Here, first statement opens a file called data and attaches it to
cout<<ch;
the stream infile. This file can then be used for input
ch=fin.get();
operations. The second statement opens a file called results
}
and attaches it to stream outfile. This file can only be used
fin.close();
for output operations. Once the infile and outfile streams
are created and connected to corresponding files,
return 0;
statements of the form:
}
outfile<< “Sum”;
infile>>num;
Example 3:
can be used to write data items to the output file results #include<fstream>
and to read data from input file data. After completing the #include<iostream>
input-output operations, the file may be closed by closing using namespace std;
the corresponding stream. outfile.close(); infile.close();
class student
C++ allows the files to be opened in different modes. {
Hence, the open() function can specify the mode of opening int id;
as well. The statement invoking open can be written as: char name[30];
stream-object.open(“filename”, mode); public:
The mode argument specifies the purpose for which the file void getdata()
is opened. The file mode parameter is defined in ios class {
and can take any of the following values: cout<<"enter id and name:"<<endl;
cin>>id>>name;
}
};
int main()
{
student s;
ofstream file;
file.open("Student.dat");
char ch;
do
{
s.getdata();
file.write((char *)&s,sizeof(s));
cout<<"record created"<<endl;
cout<<"Do you want any more record[y/n]";
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in
cin
istream&seekg(long); Form 1 >>ch
seekg()
istream&seekg(long, seek_dir); Form 2 ;
}wh
ofstream&seekp(long); Form 1 ile(c
seekp()
ofstream&seekp(long, seek_dir); Form 2 h=='
y');
file.
tellg() long tellg() clos
e();
int main()
{
student s;
ifstream file;
file.open("Student.dat");
file.read((char *)&s,sizeof(s));
cout<<"id"<<"\t"<<"name"<<endl;
while(!file.eof())
{
s.putdata();
file.read((char *)&s,sizeof(s));
}
file.close();
return 0;
}
RANDOM ACCESS
H.O. : B-5,Dev nagar ,opp. Kamal & company ,gopalpura ,Jaipur Tel : 0141-2708941 , Mob : 9887755436, 9413223636 Visit us at : www.fluxeducare.in