Pointers
Pointers
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 arithimatic operator available for use with pointer can be classified as :
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.
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)
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.
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.
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>
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 :-
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.
# 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.
# 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.