Chapter 2 - Pointers, Virtual Functions
Chapter 2 - Pointers, Virtual Functions
Chapter 2 - Pointers, Virtual Functions
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
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
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;
…
}