Download as pdf or txt
Download as pdf or txt
You are on page 1of 24

Objectives

 Pointers and Strings


 Pointers to Objects
 This Pointer
 Virtual Functions
Pointers and Strings

 Pointers are efficient to access two dimensional and multi-


dimensional arrays in C++.
 There is a definite relationship between arrays and pointers.
 C++ also allows us to handle the special kind of arrays, i.e.
string with pointers.
 String is one dimensional array of characters, which starts with
the index 0 and ends with null character ‘\0’ in C++.
 A pointer variable can access a string by referencing to its first
character.
 There are two ways to assign a value to a string:
 Use the character array or
 Variable of type char * .
Pointers and Strings

 Let us consider the following declarations:


 char num[ ] = “one”;

 const char *numptr = “one”;

 The first declaration creates an array of four characters,


which contains the characters ‘o’,’n’,’e’,’\0’.
 Whereas the second declaration generates a pointer
variable, which points the first character,i.e. ‘o’ of the
string.
Reverse a string using pointers and arrays

#include<iostream.h> //string reverse


#include<string.h> int len1 = len / 2;
void main( ) for(i=0;i<len1;i++)
{ {
char str[ ] = “Test”; str[i]=str[i]+str[len-i];
int len = strlen(str); str[len-i]=str[i]-str[len-1];
for(int i=0;i<len;i++) str[i]=str[i]-str[len-1];
{ }
cout<<str[i]<<i[str]<<*(str+1) cout<<“ the reverse string is :”<<str;
<<*(i+str);
} } OUTPUT
cout<<endl;
TTTTeeeesssstttt
The reverse string : tesT
Pointers to Objects

 A pointer can point to an object created by a class.


 item x;

 Here item is a class and x is an object of class item.


 Similarly we can define a pointer of type item as follows
 item *it_ptr;

 Object pointers are useful in creating objects at run time.


 We can also use an object.
Pointers to Objects

 Consider the following void show( )


declaration {
class item cout<<“code :
{ ”<<code<<“\n”<<“price:”
int code; <<price<<“\n\n”;
float price; }
public: };
void getdata(int a,float b)
Now Declare the variable x of class item
{ And a pointer ptr to x as follows :
code=a; price=b;
item x;
} Item *ptr = &x;
Pointers to Objects

 We can refer the member function of item in two ways:


 By using the dot operator and the object
 x.getdata(100,75.50);
 x.show( );
 And by using the arrow operator and the object pointer.
 Ptr->getdata(100,75.50) ;
 Ptr->show( );

 Since *ptr is an alias of x, we can also use the following


method : (*ptr).show( );
 The parentheses are necessary b’coz the dot operator has
higher precedence than the indirection operator *.
Pointers to Objects

 We can also create the objects by using pointers and new


operator as follows :
 item *ptr = new item ;
 This statement allocates enough memory for the data
members in the object and assign the address of memory
sapce to ptr. Then ptr can be used to refer the members.
 ptr -> show ( );
Pointers to Objects

#include<iostream.h> void show( )


class item {
{ cout<<“code :
int code; ”<<code<<“\n”<<“price:”
float price; <<price<<“\n\n”;
public: }
void getdata(int a,float b) };
{
code=a; price=b;
}
Pointers to Objects
const int size = 2 ; for(i=0;i<size;i++)
int main( ) {
{ cout<<“ Item :”<<i+1<<“\n”;
item *p = new item[size]; d->show( );
item *d = p; p++;
int x,i; }
float y; return 0;
for(i=0;i<size;i++) }
{ Input code and price for item 1 40 500
Input code and price for item 2 50 600
cout<<“Input code & price for
Item : 1
item ”<<i+1; Code : 40
cin>>x>>y; Price : 500
p->getdata(x,y); Item : 2
Code : 50
p++; Price : 600
}
this Pointer

 C++ uses a unique keyword called this to represent an


object that invokes a member function.
 this is a pointer that points to the object for which this
function was called.
 For example, the function call A.max( ) will set the
pointer this to the address of object A.
 This unique pointer is automatically passed to a member
function when it is called.
 The pointer this acts as an implicit argument to all the
member functions.
this Pointer

 Consider the following simple example


class abc
{
int a
…………
};

 The private variable ‘a’ can be used directly inside a


member function ,like
 a= 123;
 We can also use following statement to do the same job :
 this->a = 123;
this Pointer

 Since C++ permits the use of shorthand from a =123, we


have not been using the pointer this explicitly so far.
 However, we have been implicitly using the pointer this
when overloading the operators using member functions.
 Recall that, when a binary operator is overloaded using a
member function, we pass only one argument to the
function.
 The other argument is implicitly passed using the pointer
this.
 One important application of the pointer this is to return
the object it points to.
this Pointer

 For example, the statement return *this; inside a member


function will return the object that invoked the function.
 This statement assumes importance when we want to compare
two or more objects inside a member function and return the
invoking object as a result.
person & person : : greater (person & x)
{
if(x.age > age)
return x; // argument object
else
return *this; // invoking object
}
this Pointer

 Suppose we invoke this function by the call


 max = A.greater(B) ;

 The function will return the object B(argument object) if


the age of the person B is greater than of A, otherwise, it
will return the object A (invoking object) using the pointer
this.
 Remember, the dereference operator * produces the
contents at the address contained in the pointer.
this Pointer
#include<iostream.h> person & person :: greater (person
#include<string.h> &x)
class person {
{ if(x.age>=age)
char name[20]; return x;
float age; else
public: return *this;
person(char *s,float a) }
{ void displa( )
strcpy(name,s); {
age = a; cout<<“name : ”<<name<<“\n”;
} cout<<“age :”<<age<<“\n”;
}
};
this Pointer
void main( )
{ OUTPUT
person p1(“John”,37.50),
p2(“Ahmed”,29.0),
p3(“Hebber”,40.25); Elder Person is :
Name : Hebber
Age : 40.25
person p = p1.grater(p3);
cout<<“Elder Person is :\n”; Elder Person is :
p.display( ); Name : John
Age : 37.5
p = p1.grater(p2);
cout<<“Elder Person is :\n”;
p.display( );

}
Virtual Functions

 Polymorphism refers to the property by which objects


belonging to different classes are able to respond to the
same message, but in different form.
 An essential requirement of polymorphism is therefore the
ability to refer to objects without any regard to their
classes.
 If the appropriate member function could be selected
while the program is running. This is known as run time
polymorphism.
 To achieve run time polymorphism in C++ virtual function
is used.
Virtual Functions

 When we use the same function name in both the base and
derived classes, the function in base class is declared as
virtual using the keyword virtual preceding its normal
declaration.
 When a function is made virtual, C++ determine 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.
Virtual Functions
#include<iostream.h> class derived : public base
class base {
{ public:
public: void display( )
void display( ) {
{ cout<<“\nDisplay Derived”;
cout<<“\nDisplay Base ”; }
} virtual void show( )
virtual void show( ) {
{ cout<<“\nShow Derived”;
cout<<“\nShow Base”; }
} };
};
Virtual Functions

void main( )
OUTPUT
{
base b;
derived d; bptr points to base
base *bptr;
cout<<“\nbptr points to base\n”; Display Base
bptr = &b; Show Base
bptr -> display( );
bptr -> show( ); bptr points to derived
cout<<“\nbptr points to derived\n”; Display Base
bptr = &d; Show Derived
bptr -> display( );
bptr -> show( );
}
About bptr

 When bptr is made to point to the object D, the statement


bptr -> display ( ); calls only the function associated with
the Base (i.e Base : : display ( )).
 Whereas, the statement bptr -> show( ); calls the derived
version of show( ).
 This is because the function display( ) has not been made
virtual in the base class.
Rules For Virtual Function

 The virtual functions must be members of 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 prototype of the base class version of a virtual function
and all the derived class versions must be identical.
 If the 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.

You might also like