Oops Unit 2
Oops Unit 2
2
INHERITANCE: EXTENDING CLASSES
Why inheritance?
Supports Extensibility and reusability.
3
Defining derived classes:
class derived-class-name : visibility-mode base-class-name
{
…………//
………..// members of derived class
………..//
};
5
SINGLE INHERITANCE
6
Example of public derivation:
7
Private derivation example:
Adding more members to a class(by private derivation)
• If the derived class is inherited using private access specifier then all the
public and protected members of the base class will become the private
members of the derived class.
8
• Only the objects of derived class can access the private members of
their class
9
MULTIPLE INHERITANCE
It is a process of deriving one class from more than
one base class.
A class can inherit the attributes of two or more
classes.
10
Example :
11
Child inheriting the physical feature of one parent and the intelligence
of another.
Example:
12
AMBIGUITY RESOLUTION IN INHERITANCE
13
Note: This can be solved by defining a named instance within
the derived class using class resolution operator.
15
16
Modes of Inheritance
17
MAKING A PRIVATE MEMBER INHERITABLE
C++ provides a third visibility modifier, protected,which
serve a limited purpose in inheritance.
A member declared as protected is accessible by the
member functions within its class and any class immediately
derived from it.
It cannot be accessed by the fuctions outside these two
classes.
18
EFFECT OF INHERITANCE ON THE VISIBILITY OF MEMBERS
19
BASE CLASS (PROTECTED DERIVATION)
20
ACCESS MECHANISM IN CLASSES
21
Public Inheritance
Specified between two classes as:
Protected Inheritance
class Car
Specified : protected
between two classes as:
Vehicle
23
HIERARCHICAL INHERITANCE
24
HYBRID INHERITANCE
Two or more types of inheritances are applied to
design a hybrid model.
Multi-level
inheritance
Multiple inheritance
25
Class test : public student
{
…………….
}
Class result : public test ,public sports
{
…………….
};
Class sports
{
protected:
float score;
public:
void get_score(float);
void put_score(void);
}; 26
VIRTUAL BASE CLASSES
class A //
Multipath inheritance grandparent
{
……
……
};
class B1 : public A //parent
1
{
…….
……
};
class B2 : public A //parent
2
{
……
……
};
class C : public B1,public B2 //child
27
{
…… //inherits public functions
from class A,B1 and B2
The child has two direct base classes parent 1 and parent 2
which themselves have a common base class grandparent.
The child inherits the triats of grandparent through two
separate paths.
Here the grandparent class is called the indirect base class.
All the public and protected members are inherited twice
each via parent1 and parent2.
This leads to ambiguity and should be avoided.
Thus the common base class is made as virtual base class.
30
ABSTRACT CLASSES
An abstract class is one that is not used to create any
objects of its own but it solely exists to act as a base
class for other classes that means the abstract class
must be a part of some inheritance hierarchy.
Abstract class can be identified by the following ways:
Either it is followed by a keyword abstract, or
It is a class without instance, or
It contains atleast one pure virtual function.
Example:
31
General form of abstract class
{ {
public: public :
void spec() void spec()
{ {
//LMV defn of spec function //TW defn of spec
function
} }
}; }; 32
CONSTRUCTORS IN DERIVED CLASS
Constructors play an important role in initializing
objects.
If the default constructor without argument is declared
in the base class then the derived class need not have
a constructor function.
The compiler by default calls the base class
constructor.
Example:
33
PARAMETERIZED CONSTRUCTOR
Baseclass :: constructor(parameters) 34
General form of defining a derived constructor is:
Example :
D(int a1, int a2, float b1, float b2, int d1) : A(a1, a2), B(b1, b2)
{
d = d1; //body of derived class constructor
}
main()
{
D objD(5, 12, 2.5, 7.54, 30); 35
}
Below given is another method of initializing the class object.
37
POINTERS, VIRTUAL FUNCTIONS AND POLYMORPHISM
Pointers to variables
A pointer is a derived data type that refers to another data variable by
storing the variables memory address rather than data.
Declaring and initializing pointers:
data-type *pointer-variable;
38
POINTERS TO OBJECTS
A pointer can point to an object created by a class.
Object pointers are useful in creating objects at run time.
With this the object pointers can access the public members
of an object.
Example:
39
Pointers can be used to dynamically create objects and allocate
memory.
We can also create an array of objects using pointers using the new
operator.
Example:
40
this POINTER
41
Example of this pointer
42
This pointer is used to distinguish between the data
members and the arguments of the function(local
variables)
Examples:
43
POLYMORPHISM
The word polymorphism means having many forms.
Polymorphism is the ability of a message to be displayed in more than one
form.
Polymorphism is one of the important features of Object Oriented
Programming.
In C++ polymorphism is mainly divided into two types:
• Compile time Polymorphism
• Runtime Polymorphism
44
When there are multiple functions with same name but different
parameters then these functions are said to be overloaded.
Functions can be overloaded by change in number of
arguments or/and change in type of arguments.
Example(Compile time )
45
Or by simply overriding the function using the object
of the class.
Example(Compile time Polymorphism)
46
POINTERS TO DERIVED CLASS
Pointers created with the base class can also be used
to reference the objects of derived class.
A single pointer can be made to point to objects
47
48
Run-time Polymorphism
It is not known which function will be invoked till an object actually
makes the function call during the programs execution, this process
is called late or dynamic binding.
In C++ runtime polymorphisms achieved with the help of virtual
functions.
49
VIRTUAL FUNCTIONS
Polymorphism is the ability to refer to objects without any regards to
their classes.
Thus pointer to the base class is used to refer to all the objects of
the different derived classes.
Thus to implement runtime polymorphism we have to use virtual
functions with the pointer concept.
50
Note: Run time polymorphism is achieved only when a virtual function
is accessed through a pointer to the base class.
51
52
53
Virtual functions created for implementing late binding must obey
some basic rules that satisfy the compiler requirements.
1. The virtual functions must be the members of some class.
2. They cannot be static members.
3. They are accessed by using object pointers.
4. A virtual function can be a friend of another class.
5. A virtual function in a base class must be defined, even though it may not
be used.
6. The prototypes of the base class version of a virtual functions and all the
derived class versions must be identical, if two functions with the same
name have different prototypes C++ considers them as overloaded
functions, and the virtual function mechanism is ignored.
7. We cannot have virtual constructors, but we can have virtual destructors.
8. While a base pointer can point to any type of the derived object the
reverse is not true that is to say we cannot use a pointer to a derived class
to access an object of the base type.
9. When a base pointer points to a derived class incrementing or
decrementing it will not make it to point to the next object of the derived
class .it is incremented or decremented only relative to its base type
therefore, we should not use this method to move the pointer to the next
object.
54
10. If a virtual function is defined in the base class, it need not be necessarily
redefined in the derived class.in such cases call will invoke the base
function.
PURE VIRTUAL FUNCTION
56
Unit III
CHAPTER – 07
Function Overloading, Operator
Overloading
57
FUNCTION OVERLOADING
58
CONSTRUCTOR OVERLOADING
Constructors can be overloaded:
• An overloaded constructor provides multiple
ways to set up a new object.
• The overloaded constructor differ by the number
and type of parameters they get.
When we construct an object, the compiler decides which
constructor to invoke according to the type of the actual
parameters.
A constructor with no parameter is called a default
constructor.
59
OPERATOR OVERLOADING
C++ has the ability to provide the operators with the special
meaning for a data type. The mechanism of giving such special
meaning to an operator is known as operator overloading.
New definitions can be given to most of the C++ operators except
the following
• class member access operator( ., .* ) These operators takes names
• Scope resolution operator ( :: ) (class names) as their operand
• Size operator ( sizeof ) instead of values
• Conditional operator ( ? : )
} }
The process of overloading involves the following steps:
1. Create a class that defines data types that is to be
used in overloading operation.
2. Declare the operator function operator op() in the
public section of the class.it may be either a member
function or a friend function.
3. Define the operator function to implement the
required operations.
61
operator op (x) //for friend functions
Program on Overloading Unary Minus
62
Program on overloading == operator
63
Overloading binary operators
Overloading + operator
64
Implementation of the overloaded + operator
65
Overloading Binary operators using friends
67
MANIPULATION OF STRINGS USING OPERATORS
C and C++ implements strings using character
arrays,pointers and string functions.
Memory is allocated based on the length of the string
and then is manipulated.
C++ allows to create our own definitions of operators
that can be used to manipulate the strings similar to
any other data types.
Ex: we can use the stmts like…
string3 = string1 + string2;
if (string1 >= string2) string = string1;
68
Overloading + operator for string manipulation
69
Mathematical operations on
strings:
70
71
72
RULES FOR OVERLOADING OPERATORS
These are certain restrictions and limitations for overloading
they are:
1. Only existing operators can be overloaded. New operators
cannot be created.
2. The overloaded operator must have at least one operand
that is of user-defined type.
3. Overloaded operators follow the syntax rules of the original
operators. They cannot be overridden.
4. There are some operators that cannot be overloaded.
5. We cannot use friend functions to overload certain
operators, however member functions can be used to
overload them.
(= ( ) [ ] -> )
6. Unary operators, overloaded by means of a member
function, take no explicit arguments and return no explicit
values, but, those overloaded by means of a friend function,
take one reference argument(object relevant to the class)
7. Binary operators overloaded through a member function
73
take one explicit argument and those which are overloaded
through a friend function take two explicit argument.
8. When using binary operators overloaded through a
member function, the left-hand operand must be an object
of the relevant class.
9. Binary arithmetic operators such as +, -, *, and / must
explicitly return a value. They must not attempt to change
their own arguments.
74
CHAPTER 7-TEMPLATES
Templates are the new concept that enables us to
define generic classes and functions and thus provide
support for generic programming.
A template can be used to create a family of classes or
functions.
A template can be considered as a kind of macro.
A class template for an array class would enable us to
create arrays of various data types such as int array,
float array.
There are 2 types in it:
1. Class template
2. Function template
75
Class Template definition:
template<class T>
class classname
{
//…..
//class member specification
//with anonymous type T
//whenever appropriate
//…..
};
76
Program to find the dot product of two vectors:
77
Program to illustrate the use of template class
78
Data type can be changed in the main and need not be
redefined in the program function definition.
The template function type T will now take the reference data
type as float.
79
CLASS TEMPLATE WITH MULTIPLE PARAMETERS
Template<class T1, class T2,..>
Class classname
{
…..
……(body of the class)
……
}
Example:
81
Default template object types as arguments to the template
82
FUNCTION TEMPLATES
Function templates are special functions that
can operate with generic types.
This allows us to create a function template
whose functionality can be adapted to more
that one type or class without repeating the
entire code for each type.
The simple idea is to pass data types as a
parameter so that we don’t need to write
same code for different data types.
We write a generic function that can be used
for different data types.
83
Function Template Syntax:
84
Program to demonstrate Function template for Swap
function
85
FUNCTION TEMPLATES WITH MULTIPLE PARAMETERS
86
OVERLOADING OF TEMPLATE FUNCTIONS
void display(int x)
{
cout<<“Explicit display”<<x<<“\n”;
}
int main( )
{
display(100); //explicit display
display(12.34); //display1
display(100,12.34); //display2
display(‘C’); //display1
return 0;
}
88
INTRODUCTION TO THE STANDARD TEMPLATE LIBRARY
The Standard Template Library (STL) is one of the most
important features added to C++ in recent years.
STL provides general-purpose, templatized classes and
functions that could be used as a standard approach for
storing and processing of data and it implements algorithms
and data structures
STL components are defined in the namespace std and using
it will inform the compiler that we intent to use STL library.
At the core of the STL are three foundational items:
Containers
Algorithms
Iterators
These items work in conjuction with one another to provide
off-the-shelf solutions to a variety of programming problems.
89
Relationship between the three STL
components
90
A container is an object that actually stores data. It is a way data is
organised in memory.
An algorithm is a procedure that is used to process the data
contained in the containers.
An iterator is an object that points to an element in a container.
Conceptually, iterators are the linker between these two components.
They let any algorithm interact with any container.
you can combine every kind of container with every kind of algorithm.
91
CONTAINERS
93
1. Sequence Containers:
94
2. Associative Containers:
96
ALGORITHMS
Algorithms are functions that can be used generally across a
variety of containers for processing their content.
Although each container provides functions for its basic
operations, STL provides more than sixty standard algorithms to
support more extended or complex operations.
Standard algorithms also permit us to work with two different
types of containers at the same time.
STL algorithm, based on the nature of operations they perform, may
be categorized as under :
Retrieve or nonmutating algorithms
Mutating algorithms
Sorting algorithms
Set algorithms
Relational algorithm
97
ITERATORS
Iterators act like pointers and are used to access elements of
the container.
We use iterators to move through the contents of containers.
Iterators are handled just like pointers. We can increment or
decrement them as per our requirements.
Iterators connect containers with algorithms and play a vital
role in the manipulation of data stored in the containers.
They are often used to pass through from one element to
another, this process is called iterating through the container.
There are five types of iterators:
1.Input
2.Output
3.Forward
4.Bidirectional
5.Random
98
Iterators and their characteristics:
99
Iterators are pointer-like entities used to access the individual elements in a
container.
Iterators are moved sequentially from one element to another element.
This process is known as iterating through a container.
100
Iterator Categories
Iterators are mainly divided into five categories:
Input iterator:
• An Input iterator is an iterator that allows the program to read the values from the container.
• Dereferencing the input iterator allows us to read a value from the container, but it does not
alter the value.
• An Input iterator is a one way iterator.
• An Input iterator can be incremented, but it cannot be decremented.
Output iterator:
• An output iterator is similar to the input iterator, except that it allows the program to modify a
value of the container, but it does not allow to read it.
• It is a one-way iterator.
• It is a write only iterator.
Forward iterator:
• Forward iterator uses the ++ operator to navigate through the container.
• Forward iterator goes through each element of a container and one element at a time.
Bidirectional iterator:
• A Bidirectional iterator is similar to the forward iterator, except that it also moves in the
backward direction.
• It is a two way iterator.
• It can be incremented as well as decremented.
Random Access Iterator:
• Random access iterator can be used to access the random element of a container. 101
• Random access iterator has all the features of a bidirectional iterator, and it also has one more
additional feature, i.e., pointer addition. By using the pointer addition operation, we can access
the random element of a container.
THANK YOU
102