Objected Oriented Programming With C++: (India) Private Limited, New Delhi
Objected Oriented Programming With C++: (India) Private Limited, New Delhi
UNIT I
Introduction: A Look at procedure oriented programming-Object Oriented Programming
Paradigm-Basic concepts of Object Oriented Programming-Benefits of OOP-Application of
OOP.
Simple I/O Operation: cin and cout statements.
UNIT II
Classes and Objects: Structure of C++ Program-Specifying a class-Defining member
functions-Static data members and static member functions-Object as function arguments-
Friendly functions.
UNIT III
Constructors and Destructors: Constructors-Parameterized constructors-Multiple constructors
in class-Destructors.
Operator overloading: Defining operator overloading-overloading unary operators-
overloading binary operators, overloading binary operators using friends-Rules for operator
overloading-Type conversion.
UNIT IV
Inheritance: Defining derived classes-Single Inheritance-Multilevel inheritance-Multiple
inheritance.
Pointers: Declaring and initializing pointers-pointers expressions and pointer arithmetic –
using pointers with arrays and strings-this pointer-pointers to derived classes.
UNIT V
Virtual functions and Pure Virtual functions.
Working with Files: Introduction-Classes for file stream operators-Opening and Closing a
File - checking for eof() - File Modes-get () and put () functions- Binary files - read and
functions-reading and writing a class object.
1
UNIT I
1.1 INTRODUCTION: A LOOK AT PROCEDURE ORIENTED PROGRAMMING
Procedure Oriented Programming(POP) vs Object Oriented Programming(OOP)
Procedure Oriented Programming :-
Procedure Oriented Programming (POP) approaches the problem as a sequence of things to
be done such as reading, calculating and printing. The primary focus is on Functions.
Procedure oriented programming basically consists of writing a set of instructions for the
computer to follow, and organizing these instructions into groups are known as functions.
Functions are defined to accomplish the tasks to be carried out. (Figure 1.1)
Main program
Function 1 Function 2
2
Object-Oriented Problem Solving Approach
It consists of identifying objects and how to use these objects in the correct sequence to solve
the problem. Object-oriented problem solving consist of designing objects that helps to solve
a specific problem. A message to an object causes it to perform its operations and solve its
part of the problem.
The object-oriented problem solving approach, in general, can be divided into following four
steps.
Identify the problem
Identify the objects needed for the solution
Identify messages to be sent to the objects
Create a sequence of messages to the objects that solve the problem.
3
Data is represented as properties of the object and behavior as methods. When an object
receives a message, it determines what method is being requested and passes control to the
method. An object has as many methods as it takes to perform its designed actions.
Methods that operate on specific objects are instance methods and messages that invoke
instance methods are called instance message. Methods that operate on specific classes are
class methods.
Data
Functions
Object A
Data Data
Functions Functions
Object B Object C
4
The object oriented programming can be defined as an approach that modularizes programs
by creating partitioned memory area for both data and functions (Figure 1.3). The modules
can be used as templates for creating other modules if needed. Thus, an object is considered
to be a partitioned area of computer memory that stores data and set of operations that can
access that data. Since the memory partitions are independent, the objects can be used in a
variety of different programs without modifications.
5
Object contains data and the code to manipulate that data.
An object can be considered a "thing" that can perform a set of activities that defines
the object's behaviour or characteristics.
The object's interface consists of a set of commands, each command performing a
specific action.
An object asks another object to perform an action by sending it a message. The
requesting (sending) object is referred to as sender and the receiving object is referred
to as receiver.
Control is given to the receiving object until it completes the command; control then
returns to the sending object.
A message can also contain information the sending objects needs to pass to the
reviewing object, called the argument in the message.
A receiving object always returns a value back to the sending object. This returned
value may or may not be useful to the sending object.
Classes
Classes are user defined data type.
Object can be made as a user defined data type with the support of a class.
Objects are the variables of the data type class.
A created class can contain any number of objects.
A class is a collection of objects of similar type.
Each object is connected with the class with which it was created.
Syntax for creating an object from class is
Classname Objectname
Example: Car, Bus, Motor bike are members of the class Vehicle. If Vehicle is defined as a
class, then objects can be created as follows:
Vehicle Car
Object oriented languages allow the programmer to specify self contained units and specify
them as objects which are made up of data and the methods or operations which can be
performed on the object. A computer language is object-oriented if they support the following
properties:
6
Encapsulation
Encapsulation is the process of hiding data of a class from objects.
Encapsulation bundles the actions and attributes together as a single unit.
The advantage of encapsulation is that the implementation is not accessible to the
client.
The user knows only the functionality of encapsulated unit and information to be
supplied to get the result.
Encapsulation supports information hiding by making use of the three access
specifiers of a class.
7
Types of Inheritance:
o Single Inheritance : A subclass derives from a single super-class.
Y
o Multiple Inheritance : A subclass derives from more than one super-classes.
X Y
Z
o Multilevel Inheritance : A subclass derives from a super-class which in turn
is derived from another class and so on.
Z
o Hierarchical Inheritance : A class has a number of subclasses each of which
may have subsequent subclasses, continuing for a number of levels, so as to
form a tree structure.
X1 X2 X3
X1
X2 X3
X4
8
Exception Handling
Exception handling is a feature of OOP, to handle unresolved exceptions or errors produced
at runtime.
Polymorphism
Polymorphism is originally a Greek word that means the ability to take multiple
forms.
It implies using operations in different ways, depending upon the instance they are
operating upon.
Polymorphism allows objects with different internal structures to have a common
external interface.
Generalization
In the generalization process, the common characteristics of classes are combined to
form a class in a higher level of hierarchy,
Subclasses are combined to form a generalized super-class.
It represents an “is – a – kind – of” relationship.
Specialization
Specialization is the reverse process of generalization.
Distinguishing features of groups of objects are used to form specialized classes from
existing classes.
The subclasses are the specialized versions of the super-class.
Message Passing
Objects in a system may communicate with each other using message passing.
The features of message passing are:
o Message passing between two objects is generally unidirectional.
o Message passing enables all interactions between objects.
o Message passing essentially involves invoking class methods.
Link
A link depicts the relationship between two or more objects.
A link represents a connection through which an object collaborates with other
objects.
9
Through a link, one object may invoke the methods or navigate through another
object.
Association
Association is a group of links having common structure and common behavior.
Association depicts the relationship between objects of one or more classes.
Degree of an Association
Degree of an association denotes the number of classes involved in a connection.
Degree may be unary, binary, or ternary.
o A unary relationship connects objects of the same class.
o A binary relationship connects objects of two classes.
o A ternary relationship connects objects of three or more classes.
10
and it leads toward dynamic behaviour of OOP codes making it more suitable to real
time system.
Simulation and Modelling - in the area of System modelling where criteria for OOP
approach is used. Representing a system is very easy in OOP approach
Hypertext And Hypermedia - Hypertext and hypermedia is another area where OOP
approach is used. Its ease of using OOP codes that makes it suitable for various media
approaches.
Decision support system - Decision support system is an advance and complex Real
time system where OOPS can be applied.
CAM/CAE/CAD System - Computer has wide use of OOP approach due to time
saving in writing OOP codes and dynamic behaviour of OOP codes.
Office Automation System - Embeded systems make it easy to use OOP for
automated system.
AI and expert system - It is mixed system having both hypermedia and real time
system.
Real-time Business System- OOP has gained importance in the area of on-line
business via Internet.
The various differences between the procedure oriented programming and Object Oriented
programming are listed in Table 1.1.
Table 1.1 Difference between Procedure Oriented programming: and OOP
POP OOP
follows a top down approach follows a bottom up approach
Importance is given to the sequence of things Importance is given to the data
to be done
larger programs are divided into functions larger programs are divided into objects
most functions share global data. mostly the data is private
importance to algorithm rather than data importance to data rather than algorithm
Example: Pascal and C Example: C++ and Java
11
1.6 SIMPLE I/O OPERATION: CIN AND COUT STATEMENTS.
1.6.1 C++ BASICS
Header files are included at the beginning similar to C program. Header files contained
pre-declared function libraries, which can be used by users for their ease. iostream is a
header file which provides with input & output streams. It is represented as
#include <iostream.h>
main(), is the function which holds the executing part of program. The return type main
function is int.
cout <<, is used to print anything on screen
Comments –
o For single line comments, // is used before mentioning comment. For
example, cout<<"hello "; // This is single line comment
o For multiple line comment, enclose the comment between /* and */. For
example,
/*this is a multiple line comment
……
….
Comment ends */
Types of operators
Assignment Operator
12
o Operator '=' is used for assignment, it takes the right-hand side (called
rvalue) and copy it into the left-hand side (called lvalue). Assignment
operator is the only operator which can be overloaded but cannot be
inherited.
Mathematical Operators
o There are operators used to perform basic mathematical operations.
Addition (+) , subtraction (-) , diversion (/) multiplication (*) and modulus
(%) are the basic mathematical operators. Modulus operator cannot be
used with floating-point numbers.
Relational Operators
o These operators establish a relationship between operands. The relational
operators are : less than (<) , grater than (>) , less than or equal to (<=),
greater than equal to (>=), equivalent (==) and not equivalent (!=).
Logical Operators
o The logical operators are AND (&&) and OR (||). They are used to
combine two different expressions together.
Bitwise Operators
o There are used to change individual bits into a number. They work with
only integral data types like char, int and long and not with floating point
values.
Bitwise AND operator - &
Bitwise OR operator - |
Bitwise XOR operator - ^
Bitwise NOT operator - ~
Shift Operators
o Shift Operators are used to shift Bits of any variable. It is of three types,
Left Shift Operator - <<
Right Shift Operator - >>
Unsigned Right Shift Operator - >>>
Unary Operators
o These are the operators which work on only one operand. There are many
unary operators, but increment++ and decrement -- operators are most
used.
13
o Other Unary Operators : address of &, dereference *, new and delete,
bitwise not ~, logical not !, unary minus - and unary plus +.
Ternary Operator
o The ternary if-else? : is an operator which has three operands. For
example,
int x = 100;
x > 50 ? cout << "true" : cout << "false"
Comma Operator
o This is used to separate variable names and to separate expressions. st of
memory allocated for data types, objects and user defined data types.
***
14
UNIT II
Class declarations
SERVER
Member function definitions
15
Syntax of class declaration
class class_name
{ private :
variable declarations;
function declarations;
public :
variable declarations;
function declarations;
};
Objects are instances of class, which holds the data variables declared in class and the
member functions work on these class objects.
Classes contain data members and member functions, and the access of these data
members and variable depends on the access specifiers.
Class's member functions can be defined inside the class definition or outside the class
definition.
By default, a class has private access control.
No storage is assigned during a class definition.
Class name must start with an uppercase letter.
Access Control in Classes
Access specifiers are used to set boundaries for availability of members of class.
Access specifiers in the program, are followed by a colon.
Either one, two or all 3 specifiers can be used in the same class to set different boundaries
for different class members.
Access specifiers in C++ class are public, private and protected
Public - All the class members declared under public will be available to
everyone. The data members and member functions declared public can be
accessed by other classes too.
class PubAccess
{
public: // public access specifier
int a; // Data Member Declaration
16
void fun1( ); // Member Function
declaration
};
Private - No one can access the class members declared private outside that class.
If tried to access the private member, a compile time error will occur. By default
class variables and member functions are private.
class PriAccess
{
private: // private access specifier
int a; // Data Member Declaration
void func2( ); // Member Function
declaration
};
Protected - Class member outside the class are inaccessible but they can be accessed by
any subclass of that class. If class A is inherited by class B, then class B which is subclass
of class A can access.
class ProAccess
{
protected: // protected access specifier
int a; // Data Member Declaration
void show(); // Member Function
declaration
};
Creating objects: Once class has been defined any number of objects belonging to that class
can be created. Objects are the variable of the type class. A class is a collection of objects of
similar type. The declaration of object allocates needed memory space for the object. For
example the following class has three objects namely obj1, obj2 and obj3.
class cname
{
17
…
…
}obj1, obj2, obj3;
If function is defined inside class then declaring it first is not needed. The function can
directly be defined.
class BoxVolume
{
public:
int a;
int getVolume()
{
18
return a*a*a;
//returns volume of cube
}
};
But if the member function is defined outside the class definition then the function must be
declared inside class definition and then define it outside.
class BoxVolume
{
public:
int a;
int getVolume();
}
19
function body;
}
It can be called using the object and the direct member access . operator.
Calling using class name and scope resolution :: operator is also allowed.
These functions cannot access ordinary data members and member functions, but only
static data members and static member functions.
20
Inline functions
All the member functions defined inside the class definition are by default declared as
Inline.
Friend functions
Friend functions can have a private access to non-class functions.
A global function or a member function of other class can be declared as friend.
Friend functions are actually not class member function.
Friend functions can access private data members by creating object of the class.
When a class is made as a friend, all its member functions automatically become friend
functions.
Example :
class MyFriend
{
int i;
public:
friend void func( ); // Global function as friend
};
void func( )
{
MyFriend wf;
mf.i=100; // Access to private data member
cout << mf.i;
};
int main( )
{
func( ); // Called directly
}
21
Static data members of class are the members that are shared by all the objects of that
class.(Fig. 2.2)
Static variable
22
These functions or variables cannot access ordinary data members and member
functions.
These functions work for the class as a whole rather than for a particular object of a
class.
A static member function can be called using an object and the direct member
access . operator.
It can be called by itself, using class name and scope resolution :: operator.
Syntax – class_name :: function_name
Example :
class A
{
public:
static void f( ) { };
};
int main()
{
A::f( ); // calling member function directly with class
name
}
23
It also has indirect access, using the object name and the member name,
connected with the dot operator to other objects of the same class that are
passed as arguments.
An object can also be passed as an argument to a non-member function. The
non-member function can have access to the public member functions only
through that objects. These non-member functions cannot have access to the
private data members.
Whenever an object of a class is passed to a member function of the same
class, its data members can be accessed inside the function using the object
name and the dot operator. However, the data members of the calling object
can be directly accessed inside the function without using the object name and
the dot operator.
24
class class_name
{
...... .... ........
friend return_type function_name(arguments);
...... .... ........
};
The declaration of friend function should be made inside the body of class
(can be anywhere inside class either in private or public section) starting with
keyword friend.
It can be declared either in the public or private part of the class.
A function can be declared as a friend in any number of classes.
If a function is defined as a friend function then, the private and protected data
of class can be accessed from that function. The complier knows a given
function is a friend function by its keyword friend.
A friend function has full access rights to the private members of the class.
A class can be made a friend of another class using keyword friend. For
example:
When a class is made a friend class, all the member functions of that class
becomes friend function.
25
A friend function can be invoked like a normal function without the help of
any object.
It is not in the scope of the class to which it has been declared as friend and
hence, it cannot be called using the object of that class.
A member function of one class can be friend function of another class.
A friend function can be called by reference.
26
UNIT III
class X
{
int i;
public:
X( ); //Constructor
};
27
Copy Constructor
Default Constructor
Default constructor does not take any argument.
It has no parameter.
Syntax :
class_name ()
{
Constructor Definition
}
Example :
class Cube
{
int side;
public:
Cube()
{
side=10;
}
};
int main()
{
Cube c;
cout << c.side;
}
Output : 10
After creating the object, the constructor is called which initializes its data members. A
default constructor is used for initialization of object members
Even if a constructor is defined explicitly, the compiler will provide a default constructor
implicitly.
28
class Cube
{
int side;
};
int main()
{
Cube c;
cout << c.side;
}
Output : 0
In the above example, the default constructor provided by the compiler is called which has
initialized the object data members to default value of 0.
Characteristics of Constructors
Called automatically when the objects are created.
All objects of the class having a constructor are initialized before using.
Declared in the public section for availability to all the functions.
Default and copy constructors are generated by the compiler wherever required.
Generated constructors are public.
Can have default arguments like other C++ functions.
A constructor can call member functions of its class.
Return type cannot be specified for constructors.
Constructors cannot be inherited, but a derived class can call the base class
constructor.
Constructors cannot be static.
An object of a class with a constructor cannot be used as a member of a union.
29
Example :
class Cube
{
int side;
public: Cube(int x)
{
side=x;
}
};
int main()
{
Cube cb1(100);
Cube cb2(200);
Cube cb3(300);
cout << cb1.side;
cout << cb2.side;
cout << cb3.side;
}
In the above example, the parameterized constructor has initialized three objects cb1, cb2 and
cb3 with user defined values as 100, 200 and 300 respectively.
30
Example:
// constructor declaration
cons(int n, float m, char p);
cons(int n, float m);
cons( );
// object declaration
cons A(10,20,25,‟S‟ );
cons B( 100, 1.2);
cons C;
In the above example the compiler decides which constructor to be called based on the
number of arguments in the object. When A is created, the constructor with three arguments
is called since the declaration of the object is followed with three arguments. Similarly, for
object A and object C the constructor with two arguments and one argument is called
respectively.
3.4 DESTRUCTORS
Destructor is a class function that destroys the object as soon as the scope of object
ends.
The destructor is called automatically by the compiler when the object goes out of
scope.
In the syntax of destructor, the class name is used for the name of destructor; with
a tilde ~ sign as prefix to it.
Destructors will never have any arguments.
Characteristics
It does not take any parameter nor does it return any value.
Overloading a destructor is not possible.
A class can have only one destructor. A destructor can be defined outside the class.
Called automatically when the objects are destroyed.
Destructor functions follow the usual access rules as other member functions.
De-initializes each object before the object goes out of scope.
Cannot be inherited.
Address of a destructor cannot be taken.
31
A destructor can call member functions of its class.
An object of a class having a destructor cannot be a member of a union.
class X
{
public:
~X( );
};
class X
{
X( )
{
cout << "Called Constructor";
}
~X( )
{
cout << "Called Destructor";
}
};
int main()
{
X obj1; // Called Constructor
int i=1;
if(i)
{
X obj2; // Called Constructor
} // Destructor Called for obj2
} // Destructor called for obj1
32
For example, the functionality of „+‟ operator can be extended to strings through
operator overloading instead of using strcat() function.
Syntax:
Returntype classname :: operator operatorsymbol(argument list)
{
// function definition
}
operator Operator_name
33
+ (unary plus)
- (unary negation)
++ (increment)
-- (decrement)
To declare a unary operator function as a non-static member, declaration syntax is of
form:
ret_type operatorop( )
where
ret-type - the return type, op - one of the operators.
ret_type operatorop(arg )
void operator ++ ( )
The return type void comes first, followed by the keyword operator, followed by the operator
itself (++), and finally the argument list enclosed in parentheses. This declaration syntax
invokes the compiler to call this member function whenever the ++ operator is encountered.
++c1; // increment count
C1 // object
…
…
count //function
…
…
void operator++( ) // no arguments
{
++count;
}
34
Whenever an unary operator is used, it works with one operand. Therefore with the user
defined data types, the operand becomes the caller and hence no arguments are required.
Postfix form
When specifying an overloaded operator for the postfix form of the increment or
decrement operator, the additional argument must be of type int.
Specifying any other type generates an error.
The argument of type int that denotes the postfix form of the increment or decrement
operator is not commonly used to pass arguments. It usually contains the value 0.
The operator functions namely operator=, operator [ ], operator ( ) and operator? are non-
static member functions.
Some examples of declarations of operator functions are given below:
class X
{
X operator ++ (int);//Postfix increment
X operator ++ ( ); //Prefix increment
}
, Comma * Multiplication
!= Inequality *= Multiplication/assignment
% Modulus + Addition
35
%= Modulus/assignment += Addition/assignment
ret_type operatorop(arg )
where ret-type is the return type, op is one of the operators listed in the table, and arg is an
argument of any type.
To declare a binary operator function as a global function, its declaration syntax is of
the form:
ret_type operatorop(arg1,arg2 )
36
where arg1 and arg2 are arguments. At least one of the arguments must be of class
type.
There is no restriction on the return types of the binary operators.
Normally, user-defined binary operators return either a class type or a reference to a
class type.
Number s;
cin>> s;
s is an object of class Number and cin is an object of istream. In this statement left hand
side operand is not an object of user defined class Number. So the operator >> cannot be
overloaded using the member function of class Number. It should be implemented as friend
function.
37
Change the basic meaning of an operator is not possible. For example, redefining a
plus(+) operator to subtract one value from the other is not possible
Overloaded operators follow the syntax rules of the original operators. They cannot be
overridden.
“friend” functions cannot be used to overload certain operators like
o assignment operator „ = ‟
o function call operator „( )‟
o subscripting operator „[ ]‟
o class member access operator „->‟
Member function can be used to overload the above operators.
The following operators cannot be overloaded:
o scope operator - ::
o member selector - .
o member pointer selector - *
o ternary operator - ?:
Numbers of Operands cannot be changed. That is, Unary operator remains unary,
binary remains binary etc.
Unary operators, overloaded by a member function, take no explicit arguments and
return no explicit values.
Unary operators, overloaded by a friend function, take one reference argument - the
object of the relevant class.
Binary operators overloaded through a member function take one explicit argument
and through a friend function it takes two explicit arguments.
Binary arithmetic operators such as +,-,* and / must explicitly return a value. They
must not attempt to change their own arguments.
All overloaded operators except assignment (operator=) are inherited by derived
classes.
38
- short to int,
- int to float
- double to int
- to or from bool etc.,
For example:
short a=100;
int b;
b=a;
In the above example, the value of „aa is promoted from short to int without the need of any
explicit operator.
promotion - Converting from a data type with small size to another larger data type
guarantees the exact same value in the destination type. Example:
- short to int
- float to double
Converting from a data type with large size to another smaller data type does not
guarantee the exact same value in the destination type. Example:
- float to int : the value is truncated by removing the decimal part.
If a negative integer value is converted to an unsigned type, the resulting value
corresponds to its 2's complement bitwise representation
The conversions from/to boolean consider false equivalent to zero (for numeric types) and
to null pointer (for pointer types); true is equivalent to all other values and is converted to
the equivalent of 1.
For non-fundamental type conversions like arrays and functions it implicitly converts to
pointers. Pointers normally allow the following conversions:
- Null pointers : converted to pointers of any type
- Pointers to any type: converted to void pointers.
- Pointer upcast: pointers to a derived class: converted to a pointer of
an accessible and unambiguous base class.
Implicit conversions with classes
Implicit conversions can be controlled by the following member functions:
Single-argument constructors: allow implicit conversion from a particular type to
initialize an object.
Assignment operator: allow implicit conversion from a particular type on
assignments.
39
Type-cast operator: allow implicit conversion to a particular type.
Three types of situations might arise for data conversion between different types :
(i) Conversion from basic type to class type.
(ii) Conversion from class type to basic type.
(iii) Conversion from one class type to another class type.
(i) Basic Type to Class Type
This type of conversion is very easy. If a class object has been used as the left hand operand
of = operator, the type conversion can also be done by using an overloaded = operator in
C++.
(ii) Class Type to Basic Type
Define an overloaded casting operator for converting a class type to a basic type. The syntax
of the conversion function is as follows:
operator typename()
{
.......
....... //statements
}
40
The argument of the source class is passed to the destination class for the purpose of
conversion.
The conversion constructor must be kept in the destination class.
The conversion can be performed in two ways :
(a) Using a constructor.
(b) Using a conversion function.
***
41
UNIT IV
Inheritance is the process by which objects of one class acquires the properties of objects of
another classes. It supports the concept of hierarchical classification. It has the capability of
one class to acquire properties and characteristics from another class.
The class whose properties are inherited by other class is called
the Parent or Base or Super class.
The class which inherits properties of other class is
called Child or Derived or Sub class.
When an existing class is inherited, all its methods and fields become available in the
new class, making the code reusable.
All members of a class except Private can be inherited.
Additional features can be added to an existing class without modifying it making it
possible by deriving a new class from the existing one. The new class will have the
combined feature of both the classes.
Before defining a subclass, the super class must be defined or must be declared before
the subclass declaration.
The public, privtate or protected Access Mode is used to specify, the mode in which
the properties of superclass will be inherited into subclass.
Example of Inheritance
Vehicle
Car
42
class Vehicle
{ public:
int wheels = 4;
};
int main()
{
Car c;
cout << c.wheels;
cout << c.speed;
}
Output :
4 100
Types of Inheritance
In C++, we have 5 different types of Inheritance. Namely,
Single Inheritance
Multiple Inheritance
Hierarchical Inheritance
Multilevel Inheritance
Hybrid Inheritance (also known as Virtual Inheritance)
Base Class
Sub Class
Single Inheritance can inherit properties by the following three access methods:
- Private Inheritance
- Public Inheritance
- Protected Inheritance
43
Private Inheritance
Consider the following classes:
class A
{
......
…
….
};
class B: private A
{
…
…
…
}
In the above class definition, all the public parts and all the protected parts of class A
become private members/parts of the derived class in B.
No private member of class A can be accessed by class B.
A public function can be accessed by any object, but private function can be used only
within the class hierarchy.
Public Inheritance
Consider the following classes:
class A
{
........
……
};
class B: public A
{
…
…
};
In the above class definition, all the public and protected parts of class A become public and
protected class in class B respectively.
44
Protected Inheritance
Consider the following classes:
class A
{
........
……
};
class B: protected A
{
…
…
};
Now, all the public and protected parts of class A become protected in class E.
No private member of class A can be accessed by class E.
From the base Class A, Class B is derived. Class B serves as the Base class for Class C. In
this case, Class B is called as the Intermediate Base Class which provides a link for the
inheritance between Class A and Class C
Multilevel Inheritance declaration:
class A
{ .....
… };
class B: public A
{ …
… };
45
class C: public B
{ …
… };
The chain A B C is called as the inheritance path. This process of creating derived class
can be extended to any number of levels. In multilevel inheritance the constructors are
executed in the order of inheritance.
Class C
class P1
{ …
… };
class P2
{ …
… };
The access_mode can be either public or private. The parent classes are separated by
comma.
In Multiple inheritance, the base classes are constructed in the order its declaration in the
derived class.
Advantages of Inheritance
Code Reusability
Method Overriding
46
Use of Virtual Keyword
where type is any valid C++ data type and var_name is the name of the pointer
variable. Following declarations declares pointers of different types :
int ∗ptr ; creates an integer pointer pointing to an integer.
In the above example, the memory address of p is stored into ptr, i.e ptr points to the memory
location of p. The expression &p will return an int pointer value because p is an integer.
Using '∗' operator, changing/accessing value being pointed to by pointer is called
Dereferencing. Thus Dereferencing refers to changing/accessing state of the pointer.
The pointer operators „&‟ and „∗‟ have a higher precedence than all other arithmetic
operators except the unary minus, which has equal precedence.
C++ Pointers Initialization
A pointer variable must not remain un-initialized. It must be initiliazed atleast with a
NULL pointer value.
The zero pointer NULL is defined in the standard file stddef.h.
Uninitialized pointers cause the system crash.
47
nullptr keyword in C++ is a null pointer constant that can be used to initialize
pointers. Example:
48
a float pointer when incremented, its value increases by eight (or the size of float on
the machine).
Pointer Arithmetic
Only two arithmetic operation, addition and subtraction, may be performed on
pointers.
A pointer either incremented or decremented for addition or subtraction respectively.
Any integer can be added or subtracted from a pointer.
Each time a pointer is incremented by 1, it points to the memory location of the next
element of its base data type.
Example: If inptr an integer pointer is currently pointing to memory address 5001 and
the int size is 2 bytes, then after the following expression inptr++; inptr will be
pointing to 5003 and not to 5002. Each time you increment iptr by 1, it will point to
the next integer. Similarly, when you decrement iptr by 1 it will point to the location
of the previous element of its base type (int here) which is at address 999.
Pointer arithmetic on variables that are not stored in contiguous memory location is
not possible.
Arrays Pointers
Refers to a block of memory Do not refer to any section of
space. memory.
Memory addresses of array The memory address that a
cannot be changed pointer refers to can be
changed.
49
Example for declaring array of pointers, each of which points to an integer:
int ∗narray[20] ;
This declaration causes an allocation of contiguous memory for 10 pointers that can
point to integers. To each of the pointers, the elements of pointer array, may be
initialized.
In the above declaration names[] is an array of char pointers whose element pointers
contains base address of respective names. That is, the element pointer names[0]
stores the base address of string "AAA", the element pointer names[1] stores the
above address of string "BBB", and so forth.
The array of char pointers is generally preferred over two dimensional array of
characters because of the following two :
o An array of pointers makes more efficient use of available memory by
consuming lesser number of bytes to store the strings.
o Exchange the positions of strings in the array using pointers can be done
easily.
50
this pointer is a constant pointer that holds the memory address of the current object.
this pointer is passed as a hidden argument to all non-static member function calls and
is available as a local variable within the body of all non-static functions.
this pointer is not available in static member functions as static member functions can
be called without any object (with class name).
Example:
class XYZ
{
int a;
…..
….. };
{…
this->a = 100;
….
return *this;
…
}
51
Example:
X *ptr; // pointer to class X
X x; // base object
Y y; // derived object
ptr =&x; // pointer points to base object
ptr = &d; // pointer points to derived object
A base pointer can point to any number of derived objects, but it cannot directly
access the members defined by the derived class.
***
52
UNIT V
Polymorphism mechanism is supported in C++ by the use of virtual functions. The concept
of virtual function is related to the concept of dynamic binding. Binding refers to binding of
actual code to a function call. Dynamic binding is a binding mechanism in which the actual
function call is bound at run-time and it is dependent on the contents of function pointer at
run time. By altering the content of function pointers, different functions having a same name
but different code can be called, which exhibits polymorphic behaviour.
Polymorphism means „one name multiple forms‟. Runtime polymorphism can be achieved by
using virtual functions. The virtual function implementation in C++ is shown as in Figure 5.1.
Polymorphism
Runtime Polymorphism
Virtual functions
Fig. 5.1 Virtual functions from Polymorphism
When the same function name is used in both the base class and the derived class, the
function in base class is declared as virtual using virtual keyword preceding its normal
declaration.
The function to be used at runtime is determined based on the type of object pointed
to by the base pointer.
If the base pointer points to different objects, different versions of the virtual fuction
can be executed.
53
Example:
class base
{…
virtual void func( )
{ ….. }
… };
int main( )
{
base B;
derived D;
base *bptr;
bptr = &B;
…
bptr ->func( );// calls base version
…
bptr = &D;
…
bptr ->func( );// calls derived version
…
}
Virtual function can be accessed through the use of a pointer declared as a pointer to the
base class.
Runtime polymorphism is achieved only when a virtual function is accessed through the
use of a pointer to the base class.
Rules for virtual functions:
Virtual function in a base class must be defined whether used or not.
Accessed using object pointers.
Must be a member of a class.
Virtual functions cannot be static members.
Can be a function of another class.
Cannot have virtual constructors
Can have virtual destructors
54
Pure Virtual Functions
Pure virtual Functions are virtual functions with no definition. They start
with virtual keyword and ends with= 0. The syntax for a pure virtual function is
virtual void func() = 0;
A pure virtual function is a function that has the notation "= 0" in the declaration of that
function.
class class_name
{…
public:
virtual void pure_virtual( ) = 0; // no function body
…
};
The "= 0" of a pure virtual function is called as the pure specifier.
The notation "= 0" indicates that the virtual function is a pure virtual function, and has
no body or definition.
Pure virtual functions cannot have a definition inside the function declaration
A class with a pure virtual function is called an abstract class.
Pure Virtual functions cannot create object of Abstract class.
Pure Virtual function must be defined outside the class definition. If defined inside the
class definition, complier error occurs.
A pure virtual function declared in a base class has no definition relative to the base class.
A class containing a pure virtual function cannot be used to declare any object of its own.
55
5.2 WORKING WITH FILES
The data is stored in devices like hard disk using the concept of files. A file is a collection of
related data stored in a particular area on a disk. Programs can be designed to perform the
read and write operations on these files. (Figure 5.2)
I/O Stream: The I/O system of C++ handles file operations. It uses file streams as an
interface between the programs and files. The stream that supplies data to the program is
called input stream and the one that receives data from the program is called output stream.
Input stream:
Input stream extracts data from the file.
The input operation involves the creation of an input stream and linking it with the
program and input file.
Output stream:
Output stream inserts data to the file.
The output operation involves establishing an output stream with the necessary links
with the program and output file.
I/P stream
O/P stream
56
this file is included in any program that uses files. The various stream classes for console I/O
operations are shown in Figure 5.3.
istream ostream
fstream
57
5.4 OPENING AND CLOSING A FILE
For using a disk file the following things are necessary:
Suitable file name
Data type and structure
Purpose
Opening Method
The filename is a string of characters that makeup a valid filename for the operating system.
It contains two parts
- primary name
- period (optional) with extension.
Examples: abc.txt, myfile.doc
For opening a file initially a file stream is created and then it is linked to the filename. A file
stream can be defined using the classes ifstream, ofstream and fstream that are in the fstream
header file. Table 5.2 describe the contents of file classes.
Table 5.2 contents of file stream classes.
filebuf - Purpose is to set the file buffers to read and write.
- Has close() and open() as members.
fstreambase - Provides operations common to file streams.
- Serves as a base for fstream, ifstream and ofstream class.
- Contains open() and close() functions.
The class to be used depends upon the purpose whether the write data or read data operation
is to be performed on the file.
A file can be opened in two ways:
- using the constructor function of the class
- using the member function open( ) of the class
Opening Files using Constructor:
While using constructor for opening files, filename is used to initialize the file stream object.
This involves the following steps:
Create a file stream object to manage the stream using the appropriate class.
- class ofstream for output stream creation
- class ifstream for input stream creation.
58
Initialize the file object using desired file name.v
Example:
ifstream infile(“inmyfile”); //input only
opens a file named “inmyfile” for input. This creates infile as an ifstream object that
manages the input stream for reading data. Similarly,
opens a file named “outmyfile” for output. This create outfile as an ofstream object that
manages the output stream. The figure 5.3 illustrates the file stream working on two separate
files.
Output stream
Disk
outmy
Program file
inmy
file
Input stream
Fig 5.4 I/O File streams on separate files
Example: Creating files with constructor function
#include <iostream.h>
#include <fstream.h>
int main()
{
ofstream outfile(“RESULT”);
…
cin >>name;
outfile <<name <<”\n”;
…
cin >>mark;
outfile <<mark <<”\n”;
outfile.close();
59
ifstream infile(“mark”);
infile >>name;
infile >>mark;
…
infile.close();
return 0;
}
File-stream-class-name stream-object-name;
stream-object-name.open (“filename”);
…
ifstream filein;
filein.open(“file1”);
cout<<”contents of file1 \n”;
while (filein)
{
filein.getline(arg1,arg2);
cout<<arg1;
}
60
filein.close();
filein.open(“file2”);
cout<<”contents of file2”;
while(filein)
{
filein.getline(arg1,arg2);
cout<<arg2;
}
filein.close();
return 0;
}
The Figure 5.5 illustrates the file streams working on multiple files concept. At a particular
time a stream can work on one file only. To work on the current file all the other files has to
be closed.
Disk
file1
Program
file2
61
o A while loop can be made to terminate when the file stream object returns a value
of zero on reaching the end-of –file condition.
o Using if condition the condition can be checked as follows:
if (fileobj.eof() !=0 )
{
exit(1);
}
It returns a non zero value if end of file condition is encountered and zero otherwise
.Therefore the above statement terminates the program on reaching the end of file.
The file_mode parameter specifies the purpose for which the file is opened. The three
important file modes are
- reading
- writing
- appending
The default values are
ios::in - reading only
ios::out writing only
The file mode parameter can take constants defined in class ios. The following table lists the
file mode parameter and their meanings.
Table 5.2 File Mode Operation Parameter
File Mode Parameter Purpose
ios::app Appending to end-of-file
ios::ate Going to end-of-file on opening
ios::binary Binary file
ios::in Opening file for read only
ios::nocreate Opening fails if file does not exist
ios::out Opening file for write only
ios::trunk Delete the contents of the file if it
exists
62
5.6 get( ) AND put( )FUNCTIONS
The file stream classes has member functions for performing the input and output operations
on files. The functions put() and get() are designed for handling a single character at a time.
put() - writes a single character to the associated stream.
get() - reads a single character from the associated stream.
Example:
int main()
{
…
char str[80];
fstream file;
file.open(“myfile”, ios::in | ios::out); // open file
…
…
file.put(str[i]);
…
char c;
…
file.get(c);
cout<<c;
…
return 0;
}
4 bytes
1 2 5 8
Fig 5.7 Character format
63
Irrespective of its size, an integer (int) character takes two bytes to store its value in the
binary form. At the same time, a 4 digit (int) will take four bytes to store it in the character
form. The binary input and output functions take the following form:
file1.read (( char * ) & V, sizeof (V));
file2.write (( char *) & V, sizeof (V));
The functions take two arguments - the address of the variable V, and the length of
that variable in bytes.
The address of the variable is pointer to character type. It must be cast to type char*
Example:
int main( )
{
…
float var;
file1.write (( char *) & var, sizeof (var));
…
file2.read (( char * ) & var, sizeof (var));
…
}
64
The stream state member uses bit fields to store the status of error conditions.
Table 6.4 Error Handling Functions
Function Return value and meaning
eof() If end of file is encountered during reading then return TRUE
else return FALSE.
fail() If an input or output operation has failed then return TRUE.
bad() Returns TRUE under the following conditions:
- an invalid operation is attempted
- any unrecoverable error has occurred.
good() Returns TRUE if error has not occurred and the system can
proceed to perform I/O operations.
Example:
{
…
ifstream myfile;
myfile.open(“XYZ”);
…
if myfile.eof() // checking end of file condition}
..
if myfile.bad() // checking for invalid operations
…
while (myfile.read(…) ) // checking for invalid
operations
***
65