Chapter 2 - Pointers, Virtual Functions

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

CHAPTER 2

POLYMORPHISM
POINTERS
 Pointer is a derived data type that refers to the address of another variable.
A pointer variable tells that where to get the data instead of telling the
actual data.
 The declaration of the pointer is based on the data type of the variable it
points to.
data-type *pointer-variable
 At any point of time a pointer variable can point to only one data type.
int *ptr;
 Here ptr contains the memory location of any integer variable.
e.g. int *ptr , a; //Declaration
ptr=&a; //Initialization
int a = 25; a p
int *p; 25 1000
p = &a;
1000 2000
cout<<"&a:"<<&a;
cout<<"p:"<<p;
cout<<"&p:"<<&p;
cout<<"*p:"<<*p;
cout<<"*(&a):"<<*(&a);
(*p)++;
cout<<"*p:"<<*p;
cout<<"a:"<<a;a
int a = 25;
int *p,**s;
p = &a;
s = &p;
cout<<"\n*p:"<<*p;
cout<<"\n*s:"<<*s;
cout<<"\n**s:"<<**s;
cout<<"\n*(*(&p)):"<<*(*(&p));
cout<<"\n***(&s):"<<***(&s);
POINTERS WITH ARRAYS
 Pointers are associated with arrays as:
 Pointers are useful to allocate arrays dynamically
 Efficient tools to access the elements of an array.
 We can declare pointers to arrays as ;
int *ptr;
ptr = number[0]; OR ptr = number;
 An array of Pointer is an array of addresses i.e all the elements of the Pointer
array points to an item of the data array. An array of Pointer is declared as

int *abc[10];
 It is an array of ten pointers ie. Addresses all of them points to an integer.
Before initializing they point to some unknown values in the memory space.
int main ()
{
int arr[5] = {10,20,30,40,50};
int *ptr;
ptr = &arr[0];
for ( int i = 0; i < 5; i++ )
{
cout <<"*(ptr+" << i <<"):";
cout <<*(ptr + i) << endl;
}
return 0;
}
POINTERS TO OBJECTS
 Just like pointers to normal variables and functions, we can have pointers
to class members (variables and methods).
class ABC int main()
{
{
ABC ob1;
public: ABC *ptr;
int a=50; ptr = &ob1;
cout << ob1.a;
};
cout << ptr->a; // Accessing
members of class with pointer
}
class demo{
int i;
public:
demo(int x){
i=x; }
int getdata(){
return i;}
};
int main()
{
demo d[3]={55,66,77};
demo *ptr=d; //similar to *ptr=&d[0]
for(int i=0;i<3;i++)
{
cout<<ptr->getdata()<<endl;
ptr++;
}
}
Practice Program

 Create a class student having private members marks, name and


public members rollno, getdata(), printdata(). Demonstrate concept
of pointer to class members for array of 3 objects.
THIS POINTER
 ‘this’ pointer represent an object that invoke or call a member function.
 It will point to the object for which member function is called.
 It is automatically passed to a member function when it is called.
 It is also called as implicit argument to all member function.
 Friend functions can not be accessed using this pointer, because friends are
not members of a class.
 Only member functions have a this pointer.
 A static member function does not have this pointer.
THIS POINTER

 Following are the situations where this pointer is used.


 When local variable’s name is same as member’s name
 To return reference to the calling object
class sample
{
int a,b;
public:
void input(int a,int b){
this->a = a + b;
this->b = a - b;
}
void output(){
cout<<"a = "<<a;
cout<<"b = "<<b;
}
};
int main()
{
sample ob1;
int a=5,b=8;
ob1.input(a,b);
ob1.output();
}
class Test
{
int x; int y;
public:
Test& setX(int a) { x = a; return *this; } //Reference to the calling object can be returned
Test& setY(int b) { y = b; return *this; }
void print() {
cout << "x = " << x ;
cout << " y = " << y;
}
};
int main()
{
Test obj1;
obj1.setX(10).setY(20); // chain function calls
obj1.print();
}
POINTERS TO DERIVED CLASS
 We can use pointers not only to the base objects but also to the objects of derived classes.
 Pointers to the base classes are type-compatible to the objects of the derived classes. Hence, A
single pointer variable of base type can be made to point to objects belonging to base as well as
derived classes.
E.g. Here B is a base class, D is Derived class.
B *cptr;
B b;
D d;
cptr=&b;
we can also make the cptr to point to object d also.
cptr=&d;
As d is an object derived from the class B
POINTERS TO DERIVED CLASS
 We can access those members of derived class which are inherited from base
class by base class pointer.
 But we cannot access original member of derived class which are not
inherited from base class using base class pointer.
 We can access original member of derived class using pointer of derived class.
VIRTUAL FUNCTIONS
 A virtual function is a member function that is declared within a base class and redefined
by a derived class.
 To create a virtual function, precede the function's declaration in the base class with the
keyword virtual.
 When virtual function accessed "normally," it behave just like any other type of class
member function. But when it is accessed via a pointer it supports run time polymorphism.
 Base class and derived class have same function name and base class pointer is assigned
address of derived class object then also pointer will execute base class function.
 After making virtual function, the compiler will determine which function to execute at run
time on the basis of assigned address to pointer of base class.
RULES FOR VIRTUAL FUNCTIONS
 The virtual functions must be member of any class.
 They cannot be static members.
 They are accessed by using object pointers.
 A virtual function can be a friend of another class.
 A virtual function in a base class must be defined, even though it may not be used.
 We cannot have virtual constructors, but we can have virtual destructors.
 The derived class pointer cannot point to the object of base class.
 When a base pointer points to a derived class, then also 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.
 If a virtual function is defined in base class, it need not be necessarily redefined in the derived class.
In such cases, call will invoke the base class.
PURE VIRTUAL FUNCTIONS
 A pure virtual function is virtual function that has no definition within the base class.
 A pure virtual function means ‘do nothing’ function.
 We can say empty function. A pure virtual function has no definition relative to the base
class.
 Programmers have to redefine pure virtual function in derived class, because it has no
definition in base class.
 A class containing pure virtual function cannot be used to create any direct objects of its
own.
 This type of class is also called as abstract class.
PURE VIRTUAL FUNCTIONS
 Syntax:
virtual void display() = 0;
OR
virtual void display() {}
ABSTRACT CLASS

 A class that contains at least one pure virtual function is called abstract
class.
 You can not create objects of an abstract class, you can create pointers
and references to an abstract class.
VIRUTAL DESTRUCTOR

 Deleting a derived class object using a pointer of base class type that has
a non-virtual destructor results in undefined behavior. To correct this
situation, the base class should be defined with a virtual destructor.
 Making base class destructor virtual guarantees that the object of derived
class is destructed properly, i.e., both base class and derived class
destructors are called.
CHAPTER 2
TEMPLATES
INTRODUCTION

 C++ templates are a powerful mechanism for code reuse, as they enable
the programmer to write code that behaves the same for any data type.
 By template we can define generic classes and functions.
 In simple terms, you can create a single function or a class to work with
different data types using templates.
 It can be considered as a kind of macro. When an object of a specific
type is defined for actual use, the template definition for that class is
substituted with the required data type.
TEMPLATES

TEMPLATES

FUNCTION TEMPLATE CLASS TEMPLATE


FUNCTION TEMPLATE
 A function template specifies how an individual function can be constructed.
 We write a generic function that can be used for different data types.
 Syntax:
template <class T>
T functionname(T arg1,T arg2)
{
function body;
}
• A generic function defines a general set of operations that will be applied to various types of
data.
• A generic function has the type of data that it will operate upon passed to it as a parameter.
• Using this mechanism, the same general procedure can be applied to a wide range of data.
• For example the Quicksort algorithm is the same whether it is applied to an array of integers
or an array of floats. It is just that the type of data being sorted is different.
• By creating a generic function, you can define, independent of any data, the nature of the
algorithm.
• Once this is done, the compiler automatically generates the correct code for the type of data
that is actually used when you execute the function.
• In essence, when you create a generic function you are creating a function that can
automatically overload itself.
• A generic function is also called a template function. When the compiler creates a specific
version of the function, it is said to have created a generated function.
• Generic functions may be overloaded.
Suppose you write a function printData:

void printData(int value){


cout<<"The value is "<<value;
}
Now if you want to print double values or string values, then you have to overload the
function:

void printData(float value){


cout<<"The value is "<<value;
}
void printData(char *value) {
cout<<"The value is "<<*value;
}
To perform same operation with different data type, we have to write same code multiple
time.
C++ provides templates to reduce this type of duplication of code.

template<class T>
void printData(T value){
cout<<"The value is "<<value;
}

We can now use printData for any data type. Here T is a template parameter that identifies a type.
Then, anywhere in the function where T appears, it is replaced with whatever type the function is
instantiated.

int i=3;
float d=4.75;
char *s="hello";
printData(i); // T is int
printData(d); // T is float
printData(s); // T is string
OVERLOADED FUNCTION TEMPLATE
 Like ordinary functions, function templates can be overloaded.
 We can have different function definitions with the same function name so that when that name is
used in a function call, a C++ compiler must decide which one of the various functions to call.
 The rules for this decision may become rather complicated, even without templates.
 Generic functions perform the same operation for all the versions of a function except the data type
differs.
 The overloading resolution is accomplished as follows:
 Call an ordinary function that has an exact match.
 Call a template function could be created with an exact match.
 Try normal overloading resolution to ordinary functions and call the one that matches.
 An error is generated if no match is found. Note that no automatic conversions are applied to
arguments on the template functions.
CLASS TEMPLATE
 Sometimes, you need a class implementation that is same for all classes, only the data types used are
different.
 Normally, you would need to create a different class for each data type OR create different member
variables and functions within a single class.
 Syntax:
template <class type>
class classname
{
type member1;
public:
type fun();
};
CLASS TEMPLATE
 The object of template class is created as follows
class name <data type> object name;
template<class Ttype> int main()
class sample {
{ sample <int>s1;
Ttype a,b; sample <float>s2;
public: s1.getdata();
void getdata() s1.sum();
{ s2.getdata();
cin>>a>>b; s2.sum();
} }
void sum();
};
• Generic classes are useful when a class contains generalizable logic.
• For example, the same algorithm that maintains a queue of integers will also
work for a queue of characters. Also, the same mechanism that maintains a
linked list of mailing addresses will also maintain a linked of auto part
information.
• By using a generic class, you can create a class that will maintain a queue, a
linked list, and so on for any type of data.
• The compiler will automatically generate the correct type of object based
upon the type you specify when the object is created.
• C++ provides a library that is built upon template classes. This library is
usually referred to as the Standard Template Library, or STL for short.
• It provides generic versions of the most commonly used algorithms and data
structures.
CLASS TEMPLATE INHERITANCE
 The template class can also act as base class.
 There are 3 cases:-
 Derive a template class and add new member to it, the base class must be of template type.

 Derive a class from non-template class add new template type members to derive class.
 Derive a class from a template base class and omit the template features in the derive class.
 This can be done by declaring the type while deriving the class.
 All the template based variables are substituted with basic data type.
SUMMARY
 C++ supports a mechanism known as template to implement the concept of generic programming.
 Template allows us to generate a family of classes or a family of functions to handle different data types.
 Template classes and functions eliminate code duplication for different types and thus make the program
development easier and more manageable.
 We can use multiple parameters in both the class templates and function templates.
 A specific class created from a class template is called a template class and the process of creating a
template class is known as instantiation.
 Like other functions, template functions can be overloaded.
 Member function of a class template must be defined as function templates using the parameters of the
class template.
 We may also use non type parameters such basic or derived data types as arguments templates.
CONTAINERSHIP
 We can create an object of one class into another and that object will be
a member of the class. This type of relationship between classes is
known as containership or has_a relationship as one class contain the
object of another class.
 And the class which contains the object and members of another class in
this kind of relationship is called a container class.
 The object that is part of another object is called contained object,
whereas object that contains another object as its part or attribute is
called container object.
CONTAINERSHIP
 Syntax:
Class a //contained class
{
..
..
}
Class b //container class
{
..
a A;

}

You might also like