Pointer & Polymorphism
Pointer :-
Pointers are variables used to store memory address of the variables. Variables stores the value and
pointer stores their addresses at which these values are located. The values stored in the pointers are integer
values. Data type of value can be any one.
Pointer are powerful tool of ‘C’ programming. There are many advantages of pointers.
1. They are very efficient.
2. They increases execution speed of program.
3. They saves memory space
4. Data processing is very fast.
5. They enable us to access variable declared outside of function.
Declaration and initialization of pointer :-
While declaring pointer we must know data type of value whose address we are going to store.
Declaration of pointer :-
Syntax : Data_Type *pointer_name;
Example : int *p;
It suggest int is a data type and * means it is pointer. Now pointer ‘p’ can store only address of any ‘int’
variable.
Initialization of pointer [ accessing pointer or Addresses of Variable ] :-
Once pointer is declared next step is to store address of variable in it by using ‘&’ operator. It takes
following form
Syntax :- pointer_name = &variable_name;
Example:- int a , *p;
P=&a;
‘&’ operator is used to determine the address of variable. Once variable is declared we can obtain its address
by preceding its name with ‘&’ operator like this &a ;
‘*’ operator is used in pointer declaration. ‘*’ indicates that it is pointer. It takes following form.
Data_Type *pointer_name;
We can also use ‘*’ to print the content of pointer i.e. original value of variable.
/* program for pointer initialization */
#include<iostream.h>
#include<conio.h>
void main ( )
{
int a=10;
int *p=&a; /*pointer p is initialized to address of a*/
clrscr ( );
/* printing value and address of variable with and without popinter*/
cout<<a<<" is stored at "<<&a;
cout<<*p<<" is stored at p;
getch( );
}
Pointer Arithmetic:-
Pointer arithmetic is concern with the pointer . basic operation like +, - ,* , / can be done using pointer
notation. As ‘*’ indicates the value at address stored in pointer. Therefore some of following operation is
possible.
Sum=*p1+*p2;
x= *p / *p2 +5;
Some operation like increment and decrement can be used with pointer.
++p1;
++*p1;
Sum+=*p;
Some operation are not allowed
p1/p2
In addition to arithmetic operation pointer can be used with comparison operator like < , > , <= , >= , = = , !=
etc.
/* program for pointer Arithmatic */
#include<iostream.h>
#include<conio.h>
void main ( )
{
int a=20,b=10;
int *p,*q;
clrscr ( );
p=&a;
q=&b;
cout<<"nPointer Arithmaticn";
cout<<"nAddition ="<<(*p + *q);
cout<<"nSubstraction ="<<(*p - *q);
cout<<"nMultiplicatipon ="<<(*p * *q);
cout<<"nDivision ="<<(*p / *q);
cout<<"nIncrement of a ="<<++*p;
cout<<"nDecrement of b ="<<--*q;
getch( );
}
Array and pointer :-
In case of array pointers are very useful actually array is collection of same type of elements. To array
we can easily store its base address that is address of 0th element. The rest of element can be easily accessed
by the pointer as array elements are stored continuously.
Example :- int a[5]={ 10 , 20 , 30 , 40 , 50 },
int *p;
p=&a[0]; /* assign pointer to address of a[0]*/
pointer stores base address i.e. address address of 0th element. If we increment pointer like p++ , we will get
next location.
Output :-
Pointer Arithmatic
Addition = 30
Substraction = 10
Multiplicatipon = 200
Division = 2
Increment of a = 21
Decrement of b =19
/* program for pointer to Array */
#include<iostream.h>
#include<conio.h>
void main ( )
{
int a[5]={10,20,30,40,50},i,sum=0;
int *p;
clrscr ( );
p=&a[0]; /* assign pointer to address of a[0]*/
cout<<"nArray Elements aren";
for(i=0;i<5;i++)
{
cout<<*p<<" is stored at " <<p;
sum=sum+*p;
p++;
}
cout<<"nSum of array elements are=“<<sum;
getch( );
}
/* program for pointer to Array printing elements in reverse order */
#include<iostream.h>
#include<conio.h>
void main ( )
{
int a[5],i,sum=0;
int *p;
clrscr ( );
cout<<"Enter any 5 nos:");
for(i=0;i<5;i++)
{
Cin>>a[i];
}
p=&a[4]; /* assign pointer to address of last element*/
cout<<"nArray Elements in reverse order aren");
for(i=0;i<5;i++)
{
cout<<*p<<" is stored at " <<p;
sum=sum+*p;
p--;
}
cout<<"nSum of array elements are="<<sum;
getch( );
}
String and pointer :-
String is one dimensional array of characters, which start with the index 0 and ends with the null
character *0’ in C++. A pointer variable can access a string by referring to its first character. As we know,
there are two ways to assign a value to a string.
/* program for finding length of string using pointer */
#include<iostream.h>
#include<conio.h>
void main ( )
{
char str[10],*p;
int i=0;
clrscr ( );
cout<<"Enter String:";
cin>>str;
p=&str[0];
while(*p!='0')
{
p++; i++;
}
cout<<"nLength of String=“<<i;
getch( );
}
Output :-
Enter String : Welcome
Length of string=7
/* program for reverese of string using pointer */
#include<iostream.h>
#include<conio.h>
void main ( )
{
char str[10],*p;
int i=0;
clrscr ( );
cout<<"Enter String:";
cin>>str;
p=&str[0];
while(*p!='0')
{
p++; i++;
}
p--; i--;
cout<<"nReverse of String=";
while(i>=0)
{
cout<<"%c",*p);
p--; i--;
}
getch( );
}
Output :-
Enter String : Welcome
Reverse of string=emocleW
Pointer to Class Object:
Class pointer can point to an object created by a class. Pointer can point to an object created by a class.
We can refer to the member functions of item by using the arrow operator and the object pointer.
#include<iostream.h>
#include<conio.h>
class person
{
char name[10];
int age;
public:
void get()
{
cout<<"Enter Name and Age : ";
cin>>name>>age;
}
void show()
{
cout<<"n name="<<name<<" Age="<<age;
}
};
void main()
{
person p,*s;
clrscr();
s=&p;
s->get(); s->show();
getch();
}
Pointers to Derived Classes
We can use pointers not only to the base objects but also to the objects of derived classes. Pointers to
objects of a base class are type-compatible with pointers to objects of a derived class. Therefore, a single
pointer variable can be made to point to objects belonging to different classes. For example, if B is a base
class and D is a derived class from B. then a pointer declared as a pointer to B can also be a pointer to D.
Consider the following declarations:
B *cptr; // pointer to class B type variable
B b; // base object
D d; // derived object
cptr = &b; // cptr points to object b
We can make cptr to point to the object d as follows:
cptr =& d; // cptr points to object d
This is perfectly valid with C++ because d is an object derived from the class B.
Although C++ permits a base pointer to point to any object derived from that base, the pointer cannot be
directly used to access all the members of the derived class.
#include<iostream.h>
#include<conio.h>
#include<string.h>
class Base
{
public:
void display()
{
cout << "n Display base ";
}
};
class Derived:public Base
{
public:
void show()
{
cout << "n Show Derived";
}
};
void main()
{
Base B,*bptr;
Derived D;
clrscr();
cout<<"n bptr points to Base n";
bptr =&B;
bptr->display(); // calls Base version
cout<<"nn bptr points to Derivedn";
bptr =&D;
bptr->display(); // calls Base version
//bptr->show(); //can't invoke derived verion
getch();
}
Polymorphism
Polymorphism is one of the crucial features of OOP. It simply means ‘one name, multiple forms’. In C++
polymorphism is mainly divided into two types:
 Compile time Polymorphism
 Runtime Polymorphism
1. Compile time
polymorphism: This type of
polymorphism is achieved by function overloading or operator overloading. The overloaded member
functions are ‘selected’ for invoking by matching arguments, both type and number. This information is
known to the compiler at the compile time and, therefore, compiler is able to select the appropriate
function for a particular call at the compile time itself. This is called early binding or static binding or
static linking. Also known as compile time polymorphism, early binding simply means that an object is
bound to its function call at compile time.
// Function volume is overloaded 3 time.
#include<iostream.h>
#include<conio.h>
float volume (float x ) // cube
{
return (x*x*x);
}
float volume (float r, float h) // cylinders
{
return (3.14*r*r*h);
}
float volume (float l, float b, float h) // rectangular box
{
return (l*b*h);
}
void main ( )
{
clrscr ( );
cout <<"volume of cube ="<< volume (2.5);
cout<<"volume of cylinder =" <<volume(1.7,2.8);
cout<<"volume of box = " <<volume (2.0,3.0,4.0);
getch ( );
}
Runtime polymorphism:
This type of polymorphism is achieved by Function Overriding.
 Function overriding on the other hand occurs when a derived class has a definition for one of the
member functions of the base class. That base function is said to be overridden.
 At run time, when it is known what class objects are under consideration, the appropriate version of
the function is invoked. Since the function is linked with a particular class much later after the
compilation, this process is termed as late binding. It is also known as dynamic binding because the
selection of the appropriate function is done dynamically at run time.
 Dynamic binding is one of the powerful features of C++. This requires the use of pointers to objects. We
shall discuss in detail how the object pointers and virtual functions are used to implement dynamic
binding.
//program for function overriding
#include<iostream.h>
#include<conio.h>
class Base
{
public:
void display()
{
cout << "n Display base ";
}
};
class Derived:public Base
{
public:
void display() //over-rided function
{
cout << "n Display Derived ";
}
};
void main()
{
Base B;
Derived D;
B.display(); //invoke base version
D.display(); //invoke derived verion
getch();
}
Virtual Function:
Polymorphism refers to the property by which objects belonging to different classes are able to respond
to the same message, but in different forms. This necessitates the use of a single pointer variable to refer to
the objects of different classes. Here, we use the base pointer to refer to all the derived objects. But, it, always
executes the function in the base class. How do we then achieve polymorphism? It is achieved using what is
known as “virtual' functions. The function in base class is declared as virtual using the keyword virtual
preceding its normal declaration. When a function is made virtual, C++ determines which function to use at
run time based on the type of object pointed to by the base pointer, rather than the type of the pointer. Thus,
by making the base pointer to point, to different objects, we can execute different versions of the virtual
function. Program illustrates this point.
#include<iostream.h>
#include<conio.h>
class Base
{
public:
virtual void display()
{
cout << "n Display base ";
}
virtual void show()
{
cout << "n show base";
}
};
class Derived:public Base
{
public:
void display()
{
cout << "n Display Derived ";
}
void show()
{
cout << "n Show Derived";
}
};
void main()
{
Base B,*p;
Derived D;
p=&B;
p->display(); //invoke base version
p->show(); //invoke base verion
p=&D;
p->display(); //invoke derived version
p->show(); //invoke derived verion
getch();
}
Rules for Virtual Functions
 The virtual functions must be members of some 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.
 The prototypes of the base class version of a virtual function and all the derived class versions must be
identical.
 We cannot have virtual constructors, but we can have virtual destructors.
 While a base pointer can point to any type of the derived object, the reverse is not true.
 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.
 If a virtual function is defined in the base class, it need not be necessarily redefined in the derived
class. In such cases, calls will invoke the base function.
Pure Virtual Functions
It is normal practice to declare a function virtual inside the base class and redefine it in the derived classes.
The function inside the base class is seldom used for performing any task. It only serves as a placeholder.
Such functions are called "do-nothing" functions.
A "do-nothing" function may be defined as follows:
virtual void display() = 0;
Such functions are called pure virtual functions. A pure virtual function is a function declared in a base
class that has no definition relative to the base class. In such cases, the compiler requires each derived class
to either define the function or re-declare it as a pure virtual function. Remember that a class containing
pure virtual functions cannot be used to declare any objects of its own. Such classes are called abstract base
classes. The main objective of an abstract base class is to provide some traits to the derived classes.

polymorphism in c++ with Full Explanation.

  • 1.
    Pointer & Polymorphism Pointer:- Pointers are variables used to store memory address of the variables. Variables stores the value and pointer stores their addresses at which these values are located. The values stored in the pointers are integer values. Data type of value can be any one. Pointer are powerful tool of ‘C’ programming. There are many advantages of pointers. 1. They are very efficient. 2. They increases execution speed of program. 3. They saves memory space 4. Data processing is very fast. 5. They enable us to access variable declared outside of function. Declaration and initialization of pointer :- While declaring pointer we must know data type of value whose address we are going to store. Declaration of pointer :- Syntax : Data_Type *pointer_name; Example : int *p; It suggest int is a data type and * means it is pointer. Now pointer ‘p’ can store only address of any ‘int’ variable. Initialization of pointer [ accessing pointer or Addresses of Variable ] :- Once pointer is declared next step is to store address of variable in it by using ‘&’ operator. It takes following form Syntax :- pointer_name = &variable_name; Example:- int a , *p; P=&a;
  • 2.
    ‘&’ operator isused to determine the address of variable. Once variable is declared we can obtain its address by preceding its name with ‘&’ operator like this &a ; ‘*’ operator is used in pointer declaration. ‘*’ indicates that it is pointer. It takes following form. Data_Type *pointer_name; We can also use ‘*’ to print the content of pointer i.e. original value of variable. /* program for pointer initialization */ #include<iostream.h> #include<conio.h> void main ( ) { int a=10; int *p=&a; /*pointer p is initialized to address of a*/ clrscr ( ); /* printing value and address of variable with and without popinter*/ cout<<a<<" is stored at "<<&a; cout<<*p<<" is stored at p; getch( ); }
  • 3.
    Pointer Arithmetic:- Pointer arithmeticis concern with the pointer . basic operation like +, - ,* , / can be done using pointer notation. As ‘*’ indicates the value at address stored in pointer. Therefore some of following operation is possible. Sum=*p1+*p2; x= *p / *p2 +5; Some operation like increment and decrement can be used with pointer. ++p1; ++*p1; Sum+=*p; Some operation are not allowed p1/p2 In addition to arithmetic operation pointer can be used with comparison operator like < , > , <= , >= , = = , != etc. /* program for pointer Arithmatic */ #include<iostream.h> #include<conio.h> void main ( ) { int a=20,b=10; int *p,*q; clrscr ( );
  • 4.
    p=&a; q=&b; cout<<"nPointer Arithmaticn"; cout<<"nAddition ="<<(*p+ *q); cout<<"nSubstraction ="<<(*p - *q); cout<<"nMultiplicatipon ="<<(*p * *q); cout<<"nDivision ="<<(*p / *q); cout<<"nIncrement of a ="<<++*p; cout<<"nDecrement of b ="<<--*q; getch( ); } Array and pointer :- In case of array pointers are very useful actually array is collection of same type of elements. To array we can easily store its base address that is address of 0th element. The rest of element can be easily accessed by the pointer as array elements are stored continuously. Example :- int a[5]={ 10 , 20 , 30 , 40 , 50 }, int *p; p=&a[0]; /* assign pointer to address of a[0]*/ pointer stores base address i.e. address address of 0th element. If we increment pointer like p++ , we will get next location. Output :- Pointer Arithmatic Addition = 30 Substraction = 10 Multiplicatipon = 200 Division = 2 Increment of a = 21 Decrement of b =19
  • 5.
    /* program forpointer to Array */ #include<iostream.h> #include<conio.h> void main ( ) { int a[5]={10,20,30,40,50},i,sum=0; int *p; clrscr ( ); p=&a[0]; /* assign pointer to address of a[0]*/ cout<<"nArray Elements aren"; for(i=0;i<5;i++) { cout<<*p<<" is stored at " <<p; sum=sum+*p; p++; } cout<<"nSum of array elements are=“<<sum; getch( ); }
  • 6.
    /* program forpointer to Array printing elements in reverse order */ #include<iostream.h> #include<conio.h> void main ( ) { int a[5],i,sum=0; int *p; clrscr ( ); cout<<"Enter any 5 nos:"); for(i=0;i<5;i++) { Cin>>a[i]; } p=&a[4]; /* assign pointer to address of last element*/ cout<<"nArray Elements in reverse order aren"); for(i=0;i<5;i++) { cout<<*p<<" is stored at " <<p; sum=sum+*p; p--; } cout<<"nSum of array elements are="<<sum; getch( ); }
  • 7.
    String and pointer:- String is one dimensional array of characters, which start with the index 0 and ends with the null character *0’ in C++. A pointer variable can access a string by referring to its first character. As we know, there are two ways to assign a value to a string. /* program for finding length of string using pointer */ #include<iostream.h> #include<conio.h> void main ( ) { char str[10],*p; int i=0; clrscr ( ); cout<<"Enter String:"; cin>>str; p=&str[0]; while(*p!='0') { p++; i++; } cout<<"nLength of String=“<<i; getch( ); } Output :- Enter String : Welcome Length of string=7
  • 8.
    /* program forreverese of string using pointer */ #include<iostream.h> #include<conio.h> void main ( ) { char str[10],*p; int i=0; clrscr ( ); cout<<"Enter String:"; cin>>str; p=&str[0]; while(*p!='0') { p++; i++; } p--; i--; cout<<"nReverse of String="; while(i>=0) { cout<<"%c",*p); p--; i--; } getch( ); } Output :- Enter String : Welcome Reverse of string=emocleW
  • 9.
    Pointer to ClassObject: Class pointer can point to an object created by a class. Pointer can point to an object created by a class. We can refer to the member functions of item by using the arrow operator and the object pointer. #include<iostream.h> #include<conio.h> class person { char name[10]; int age; public: void get() { cout<<"Enter Name and Age : "; cin>>name>>age; } void show() { cout<<"n name="<<name<<" Age="<<age; } }; void main() { person p,*s; clrscr(); s=&p; s->get(); s->show(); getch(); }
  • 10.
    Pointers to DerivedClasses We can use pointers not only to the base objects but also to the objects of derived classes. Pointers to objects of a base class are type-compatible with pointers to objects of a derived class. Therefore, a single pointer variable can be made to point to objects belonging to different classes. For example, if B is a base class and D is a derived class from B. then a pointer declared as a pointer to B can also be a pointer to D. Consider the following declarations: B *cptr; // pointer to class B type variable B b; // base object D d; // derived object cptr = &b; // cptr points to object b We can make cptr to point to the object d as follows: cptr =& d; // cptr points to object d This is perfectly valid with C++ because d is an object derived from the class B. Although C++ permits a base pointer to point to any object derived from that base, the pointer cannot be directly used to access all the members of the derived class. #include<iostream.h> #include<conio.h> #include<string.h> class Base { public: void display() { cout << "n Display base "; } };
  • 11.
    class Derived:public Base { public: voidshow() { cout << "n Show Derived"; } }; void main() { Base B,*bptr; Derived D; clrscr(); cout<<"n bptr points to Base n"; bptr =&B; bptr->display(); // calls Base version cout<<"nn bptr points to Derivedn"; bptr =&D; bptr->display(); // calls Base version //bptr->show(); //can't invoke derived verion getch(); }
  • 12.
    Polymorphism Polymorphism is oneof the crucial features of OOP. It simply means ‘one name, multiple forms’. In C++ polymorphism is mainly divided into two types:  Compile time Polymorphism  Runtime Polymorphism 1. Compile time polymorphism: This type of polymorphism is achieved by function overloading or operator overloading. The overloaded member functions are ‘selected’ for invoking by matching arguments, both type and number. This information is known to the compiler at the compile time and, therefore, compiler is able to select the appropriate function for a particular call at the compile time itself. This is called early binding or static binding or static linking. Also known as compile time polymorphism, early binding simply means that an object is bound to its function call at compile time.
  • 13.
    // Function volumeis overloaded 3 time. #include<iostream.h> #include<conio.h> float volume (float x ) // cube { return (x*x*x); } float volume (float r, float h) // cylinders { return (3.14*r*r*h); } float volume (float l, float b, float h) // rectangular box { return (l*b*h); } void main ( ) { clrscr ( ); cout <<"volume of cube ="<< volume (2.5); cout<<"volume of cylinder =" <<volume(1.7,2.8); cout<<"volume of box = " <<volume (2.0,3.0,4.0); getch ( ); }
  • 14.
    Runtime polymorphism: This typeof polymorphism is achieved by Function Overriding.  Function overriding on the other hand occurs when a derived class has a definition for one of the member functions of the base class. That base function is said to be overridden.  At run time, when it is known what class objects are under consideration, the appropriate version of the function is invoked. Since the function is linked with a particular class much later after the compilation, this process is termed as late binding. It is also known as dynamic binding because the selection of the appropriate function is done dynamically at run time.  Dynamic binding is one of the powerful features of C++. This requires the use of pointers to objects. We shall discuss in detail how the object pointers and virtual functions are used to implement dynamic binding. //program for function overriding #include<iostream.h> #include<conio.h> class Base { public: void display() { cout << "n Display base "; } };
  • 15.
    class Derived:public Base { public: voiddisplay() //over-rided function { cout << "n Display Derived "; } }; void main() { Base B; Derived D; B.display(); //invoke base version D.display(); //invoke derived verion getch(); }
  • 16.
    Virtual Function: Polymorphism refersto the property by which objects belonging to different classes are able to respond to the same message, but in different forms. This necessitates the use of a single pointer variable to refer to the objects of different classes. Here, we use the base pointer to refer to all the derived objects. But, it, always executes the function in the base class. How do we then achieve polymorphism? It is achieved using what is known as “virtual' functions. The function in base class is declared as virtual using the keyword virtual preceding its normal declaration. When a function is made virtual, C++ determines which function to use at run time based on the type of object pointed to by the base pointer, rather than the type of the pointer. Thus, by making the base pointer to point, to different objects, we can execute different versions of the virtual function. Program illustrates this point. #include<iostream.h> #include<conio.h> class Base { public: virtual void display() { cout << "n Display base "; } virtual void show() { cout << "n show base"; } }; class Derived:public Base { public: void display()
  • 17.
    { cout << "nDisplay Derived "; } void show() { cout << "n Show Derived"; } }; void main() { Base B,*p; Derived D; p=&B; p->display(); //invoke base version p->show(); //invoke base verion p=&D; p->display(); //invoke derived version p->show(); //invoke derived verion getch(); }
  • 18.
    Rules for VirtualFunctions  The virtual functions must be members of some 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.  The prototypes of the base class version of a virtual function and all the derived class versions must be identical.  We cannot have virtual constructors, but we can have virtual destructors.  While a base pointer can point to any type of the derived object, the reverse is not true.  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.  If a virtual function is defined in the base class, it need not be necessarily redefined in the derived class. In such cases, calls will invoke the base function. Pure Virtual Functions It is normal practice to declare a function virtual inside the base class and redefine it in the derived classes. The function inside the base class is seldom used for performing any task. It only serves as a placeholder. Such functions are called "do-nothing" functions. A "do-nothing" function may be defined as follows: virtual void display() = 0; Such functions are called pure virtual functions. A pure virtual function is a function declared in a base class that has no definition relative to the base class. In such cases, the compiler requires each derived class to either define the function or re-declare it as a pure virtual function. Remember that a class containing pure virtual functions cannot be used to declare any objects of its own. Such classes are called abstract base classes. The main objective of an abstract base class is to provide some traits to the derived classes.