0% found this document useful (0 votes)
12 views10 pages

Pointers

pointers in polymorphism

Uploaded by

Tasawar Ali
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views10 pages

Pointers

pointers in polymorphism

Uploaded by

Tasawar Ali
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Chapter - 4

POINTER and Polymorphism in C++


 Concept of pointer :
Pointer is a variable which is capable of storing address of another variable.Normally,
a variable directly contains a specific value but pointer contains an address of a variable
that contains a specific value.
Two operators are used to explain the basic things about pointers
1) Pointer operator (*)
2) Address operator (&)

A pointer operator can be represented by a combination of * (asterisk) with a variable. An


address operator can be represented by a combination of & with a variable.

Pointer Declaration :-
data-type *pointer_variable;
e.g.
int a ,* b
a=50;
b=&a;
cout << *b;

In above example “a” is regular variable while “b” is pointer variable which stores the
address of variable “a”. And the value stored in variable “a” is represented by “*b” .

Pointer Expressions :- a pointer is a variable and hence the general rule to assign is same
as that of other datatype variable,i.e. the pointer pointer can be expressed by assigning the
variables.
Example :-
int p,q;
int *ptr1,*ptr2;
ptr1=&p;

The memory address of variable p is assigned to the pointer variable ptr1.


Ptr2=ptr1;
The address of the ptr1 is assigned to the pointer variable ptr2.
q=*ptr1;
The content of the pointer variable ptr1 is assigned to the variable q not any
memory address.
Pointer Arthimatic :-

The arithimatic operator available for use with pointer can be classified as :

Unary operator : ++(increment)


--(decrement)
Binary operator : +(addition)
-(subtraction)
A pointer may be increment (++) and decremented (--). If pointer is incremented, it points to
next memory location in array. And if decremented then it points to previous memory
location in array.

Consider the following statement,


float *sum;
char *name;
A statement such as
sum++;or ++sum;
If sum holds the address 1000 on execution of above statement then
(1000+4)=1004 since the size of float is 4 bytes,
Similarly
Name holds the address 2000 on execution of above statement then
(2000+1)=2001 Since the size of char is 1 bytes.

Pointer initialization :-

To initialize the pointer to the base address of the string, we can assign the pointer to
the name of the string or to the address of first element of the string.
e.g.
if string is : char str[10], and pointer is : char *ptr; then to initialize the pointer we
can give either ptr = str ; or ptr = str[0];

.int s[10],*ptr;
ptr=&s[0] or ptr=s;

in above statement “s” is an array, and “ptr” is a pointer variable which stores the address of
first location of array “s”.

int a[]={1,2,3,4,5},*p=a;

Pointer to object:-
pointer to object points to an object of the class. pointer to object is a pointer
variable which is of object type.

To access individual members of objects using pointer an operator called


arrow operator () formed by combination of dash and greater than sign is used
instead of (.) dot operator.

Syntax to declare a pointer to object :


class_name *pointe_variabl_name;
Example :-.
student s1,*ptr;

The address of object in a pointer variable is stored as follows;


.ptr = &s1;
Now the member of “s1” object can be accessed by using pointer
variable with arrow operator “ “.
.ptr input();
.ptr display();

 Program to declare a class 'product' having data members as product_name


and product_price. Accept & display this data for one object using pointer to
the object. [S-11]
# include<iostream.h>
#include<conio.h>
class product //class definition
{
private:
char product_name[15];
float product_price;
public:
void get_data(void) // function to accept data
{
cout << "\n Enter product name and price : ";
cin >> product_name>>product_price;
}
void disp_data(void) // function to display data
{
cout<<"\n Product name : "<< product_name;
cout<<"\n Product price : "<< product_price;
}
};
void main(void)
{
clrscr( );
product prod, *p; // declaration of object and pointer to object
p = &prod; // initialization of pointer by assigning
// it the address of the object.
p->get_data( ); // calling member function of object.
p->disp_data( ); // using pointer with -> (arrow) operator
}
Output of Program :
Enter product name and price : printer 8000 
Product name : printer
Product price : 8000

This pointer :
 It is a predefined pointer variable within every class.
 It is a pointer to the current object i.e. the object whose member (data/ function)
is currently being accessed
 When a non static member function is called, the this pointer is automatically
passed as an implicit argument to that function and the pointer points to the
object.
The keyword this is used to access the pointer to the current object. We have to use the
arrow operator (->) in order to access the data/function members of the current object along
with this pointer as this pointer is a pointer to object.
e.g.
this->get_data( ); // calls get_data( ) method of the current object using this pointer
Example :-

class sample
{
int a;
public:
void input()
{
this a = 99;
}
void display()
{
cout << “\n The value of data member is “ << this a;
}
};
main()
{
sample s1;
s1.input();
s1.display();
getch(); }
Concept of polymorphism :- [S-10]
Polymorphism means many forms. It is the ability to take more than one form. In object
oriented programming, polymorphism refers to identically named method i.e. member
functions that have a different behavior depending on the type of object they refers.

For example, an operation may exhibit different behavior in different instances. The behavior
depends upon the types of data used in the operation.

Following figure illustrates that a single function name can be used to handle different
numbers and different types of arguments.

Shape

Draw()

Triangle (object)
Circle object Box object
Draw (triangle)
Draw(circle) Draw(box)

 There are basically two types of polymorphism.

1. Compile time polymorphism

2. Run time polymorphism.


1 Compile time polymorphism: 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. This is called early binding or static
linking. Also known as compile time polymorphism, early binding, simply means
that object is bound to its function call at compile time.

2 Run time polymorphism: The appropriate member function is selected while the
program is running; this is known as runtime function. C++ supports mechanism
known as virtual function, to achieve runtime polymorphism. At run time, when it is
known what class objects are under consideration, the appropriate version of the
function is called. Since, 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 runtime. Dynamic binding requires the use of pointers to objects.

Polymorphism

Compile
3 time polymorphism Run time polymorphism

4
Function Operator Virtual functions
5
overloading overloading
Compile time polymorphism
Run time polymorphism
(early or static binding)
(late or dynamic binding)
1) Dynamic binding means that the selection 1) Static binding simply means that an object is
of the appropriate function is done at run bound its function call at compile time.
time
2) This requires the use of pointer to objects. 2) This does not require the use of pointer to
object.
3) Dynamic/late binding is not helpful to 3) Static/Early binding is helpful to achieve
achieve greater efficiency. greater efficiency.
4) Function calls execution are slower. 4) Function calls are faster because all the
information necessary to call the function are
hardcode.
5) E.g.: Virtual function 5) E.g. Normal function calls, overloaded
function calls.

Compile Time Polymorphism:


 Function overloading :-

Function overloading allows a function to operate differently depending on


the data type and no. of arguments passed to it. When a function is overloaded, the same
function has more than one definition where the difference is either in no. of parameters or
in data types of parameters or both.
Syntax for function prototype :

return_type function_name (data_type argument1, data_type argument2,....)


e.g.

int add(int a, int b); // function add with two integer parameters
double add(double p, double q); // function add with two double parameters
float add(float a, float b, float c); // function add with three float parameters
Example :-

#include<iostream.h>
#include<conio.h>

int add(int,int);
int add(int,int,int);
double add(double,double);
main()
{
clrscr();
cout << "\n The addition of two number is " << add(10,20);
cout << "\n The addition of three number is " << add(10,20,30);
cout << "\n The addition of two double number is " << add(10.5,20.5);
getch();
return 0;
}
int add(int a, int b)
{
return(a+b);
}
int add(int a, int b,int c)
{
return(a+b+c);
}
double add(double a, double b)
{
return(a+b);
}
Function overriding :-
Overriding means base class member can be overridden by defining a derived
class member with same name as that of the base class member.The function which
is overridden works differently in the base class and the derived class.

Complier makes a decision in following way to execute member function, if


same member function exists in base class & derived class.
 If the function is invoked from an object of the derived class, then the
function in derived class is executed.
 If the function is invoked from an object of the base class, then the base
class member function is invoked.

The overridden function should have same name in base class as well as in derived
class but it can have different no. of parameters of different data types and also
different return types.
Program to illustrate the overriding of member function.

# include <iostream.h>
#include <conio.h>

// program to illustrate member function overriding

class baseclass // base class definition


{
public:
void disp(void) // base class function to be overridden
{
cout<<"\n Printing from Base class";
}
};
class derivedclass // derived class definition.
{
public:
void disp(void) // overriding base class function in derived class.
{
cout<<"\n Printing from Derived class";
}
};

void main(void)
{
clrscr( );
baseclass x; // creating object of base class
derivedclass y; // creating object of derived class
x.disp( ); // base class function invoked
y.disp( ); // derived class function invoked
}

Output of Program :
Printing from Base class
Printing from derived class
Overloading unary and binary operators. :-
Operator overloading :-

It allows to extend functionality of an existing operator to operate on user defined


data types also.The operation of operator when the operands are of user defined
data types depends upon operator overloading done in program.

Unary operator overloading : Overloading of operators operating on single


operand. There should be no arguments to the operator function.

Binary operator overloading : Overloading of operators operating on two


operands. There should be one parameter to the operator function.

Following operator can’t be overloaded :-

1) :: Scope resolution operator.


2) sizeof operator
3) ?: conditional (ternary) operator
4) .* pointer to class member operator
5) . dot operator

Operator Overloading extends the functionality of existing operators.Operator


Overloading for unary operator requires no parameter to the operator Function.
Operator Overloading for binary operator requires one parameter to the operator
function.

Syntax for declaration of operator function :-

For declaration of the operator function if declared inside class defintion.

return_ datatype operator operator_to_overload(arguments);

For declaration of the operator function if declared outside class definition.

return_ datatype class_name::operator operator_to_overload(arguments);

e.g.
int operator + (test t); // operator function to overload '+' operator

To declare a class distance to store distance in feet and inches. Inches will increment
by 1 if ++ operator is used with the object i.e. ++ operator is overloaded.

// Program to overload unary ++ operator

# include<iostream.h>
#include<conio.h>
class distance
{
private :
int feet , inch;
public :
distance(int ft, float in) // constructor function
{
feet = ft ;
inch = in ;
}
void operator ++ (void ) ; // to overload the + + operator
void disp_dist(void);
};
void distance::operator ++ (void)
{
inch ++;
if(inch>= 12) // overloading operator ++ so that inches will increment by 1
{
inch = inch-12;
feet++ ;
}
}
void distance::disp_dist (void) // function to display the distance
{
cout << " Distance in feet = "<< feet <<" \' "<< inch<<" \" "<<endl ;
}

void main(void)
{
clrscr( );
distance d1(10,10);
d1.disp_dist( );
++d1; // using ++ operator with object d1
d1.disp_dist( );
++d1;
d1.disp_dist( );
}

Output of Program :
Distance in feet = 10' 10"
Distance in feet = 10' 11"
Distance in feet = 11' 0"

Program 2 : Program to declare a class distance that will hold distance in feet and inches
and the + operator is overloaded so that when two objects of class distance are added, the
feet and inches of each will be added.

// Program to overload Binary + operator

# include<iostream.h>
# include<conio.h>
class distance
{
private :
int feet ,inch;
public :
distance(int ft, int in); // constructor function
distance operator + (distance d); // operator function to overload + operator
void disp_distance(void); // display distance in feet and inches
};
distance::distance(int ft = 0, float in = 0)
{
feet = ft;
inch = in;
}
// The ‘+’ operator needs two operands, one passed as a parameter and the
other as the implicit object
distance distance::operator + ( distance d) // operator function for + operator
{ // function returns an object of distance
int f1 = feet + d.feet ; // and has a parameter as object
int f2 = inch + d.inch;
if ( f2 >= 12)
{
while(f2>=12)
{
f2= f2-12;
f1++ ;
}
}
distance d1(f1, f2); // create an object of distance and return it
return d1;
}
void distance::disp_distance(void) // function to display the distance
{
cout << " Distance = " << feet << "\' "<<inch << "\" "<< endl;
}
void main(void)
{
clrscr( );
distance a1(11,11), a2 (10, 10) , a3;
a3 = a1 + a2;
a3.disp_distance( );
}
Output of Program :
Distance in feet = 22' 9"
 Rules for overloading operators :- [S-10]
1. Only existing operator can be overloaded. new operator cannot be created.
2. The overloaded operator must have at least one operand that is of user define type.
3. We cannot change the basic meaning of an operator. that is cannot redefine the
plus(+) operator to subtract one value from the other.
4. Overloaded operator follow the syntax rules of original operator.
5. operator can’t be overloaded :-
1) :: Scope resolution operator.
2) sizeof operator
3) ?: conditional (ternary) operator
4) .* pointer to class member operator
5) . dot operator
Run Time Polymorphism:
Virtual function:-
 A function qualified by virtual keyword.
 when a virtual function is called via a pointer.
 It allows functions in base class to be declared in each derived class.
 A pointer to an object of a base class can also point to the objects of its derived classes.
 The rule is that the compiler selects the function based on the contents of the pointer, not
on the type of pointer Virtual function should be declared in the public section of the
class.
Syntax for declaration of virtual function
virtual return_data_type function_name(<parameter list>)
{
<body of function>
}
Example :-
#include<iostream.h>
#include<conio.h>
class base // base class definition.
{
public : virtual void print( void ) // virtual function in base class
{
cout<<" \n Printing from base class";
} };
class derived : public base // defining first derived class
{
public: void print(void) // overriding virtual function.
{
cout<<" \n Printing from first derived class ";
} };
void main(void)
{
clrscr( );
base b1; // creating base class object.
derived d1; // creating an object of first derived class
base *bp; // creating pointer of base class.
cout<<"\n Base class pointer pointing to base class object";
bp=&b1; // assigning base class pointer to base class object
bp->print( ); // calls base class version of print
cout<<"\n Base pointer now points to first derived class object";
bp=&d1;
bp-> print( ); // calls first derived class version of print
cout<<"\n Base pointer now points to second derived class object ";
}
pure virtual function : a pure virtual function is a virtual function with no body. The base
class version of virtual function is never executed. This is a common situation. There is no
need for the base class version of particular function; we only use the versions of functions
in derived classes. When this is true, the body of virtual function in the base class can be
removed and the notation =0 added to the function declaration as shown below.
class sample
{
public:
virtual void display()=0; // pure virtual function
};
class today:public sample
{
public:
void display()
{
cout << "\n function of derived class :";
}};
Rules for virtual functions : [S-10]
1) The virtual function must be members of some class.
2) They cannot be static members.
3) They are accessed by using object pointer
4) The 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) We cannot have virtual constructor but can have virtual destructors.
7) While a base pointer can point to any type of the derived object, the reverse is not
true. That is, we cannot use a pointer to a derived class to access an object of the
base type.
8) If a virtual function is defined in the base class, it need not be necessarily redefined in
the derived class.

You might also like