You are on page 1of 16

Unit – IV

Pointer, Features of Pointer:


Pointers are one of the derived types in C++. some of the advantages of pointers are
given below:

 Pointers provide direct access to memory


 Pointers provide a way to return more than one value to the functions
 Pointers provide efficient techniques for manipulating data in arrays
 Pointers can be used to pass information back and forth between the calling function and
called function
 Pointers allows us to perform dynamic memory allocation and deallocation
 Pointers helps us to build complex data structures like linked list, stack, queues, trees,
graphs etc.
 Reduces the storage space and complexity of the program
 Reduces the execution time of the program

Pointer concepts:
A pointer is a constant or variable that contains the address that can be used to access data. There
are three concepts associated with the pointers they are
 Pointer constants
 Pointer values
 Pointer variables

Pointer constants:

Pointer constant is defined as an address in memory. Computers use their memory to


store programs and data. Memory is made up of a large number of cells having a fixed capacity
of storage. Each cell can hold one byte of information and has a unique number associated with it
called as address.
The computer addresses are numbered consecutively, starting from zero. The last address
depends on the memory size. Let us assume the size of the memory is 64K then,
The total memory locations = 64KB

C++ NOTES Page 1


Unit – IV

= 64 * 1KB
= 64 * 1024 bytes
= 65536 bytes (locations)
So, here the last address is 65535(started with 0).So memory can be viewed as follows

Address Memory Locations

. .

. .

. .

. .

. .

. .

65534

65535

These memory addresses are called pointer constants. so they are drawn from the set of addresses
for a computer, exist by themselves. We cannot change them. We can only use them.

Pointer value:
Whenever we declare a variable, the system allocates, an appropriate location to hold the value
of the variable somewhere in the memory.
Consider the following declaration,

C++ NOTES Page 2


Unit – IV

int i=10;
This declaration tells the C compiler to perform the following activities:
Reserve space in the memory to hold the integer value.
Associate the name i with this memory location.
Store the value 10 at this location.
We can represent i’s location in the memory by the following memory map:

i Variable Name

10 Variable value

65510 Variable address

The memory locations assigned to the variables by the system are called pointer values. For
example, the address 65510 which is assigned to the variable i is a pointer value.
Note: A variable address is the first byte occupied by the variable.

Address operator(&):
The address operator(&) extracts the address for a variable. The address operator format is as
follows.
&variablename;
Ex: to know the address of the variable n, just use &n
The format specifier of address is %u(unsigned integer). We can also use %x to know the
address of a variable.
The & operator can be used only with a simple variable or with an element of the array. If
x is an array then expressions such as &x[0], &x[i+3] are valid and represent the addresses of 0 th
and (i+3) th elements of x.
The following are illegal use of address operator
a) &125(pointing at constants)
b) int x[10];

C++ NOTES Page 3


Unit – IV

&x (pointing at arrays)


c) &(x+y) (pointing at expressions)

Indirection operator(*):

It is called as ‘Value at address’ operator. It returns the value stored at a particular


address.
It is also Known as Dereferencing Operator

Pointer variable:
A variable which holds the address of some other variable is called pointer variable. A
pointer variable should always contain the address only.

Pointer Declaration
In C++, every variable must be declared before they are used. Since the pointer variables
contain address that belongs to a separate data type, they must be declared as pointers before we
use them.

The syntax for declaring a pointer variable is as follows

data type *ptr_name;

For example,

int *p;

declares the variable p as a pointer variable that points to an integer data type. Remember that the
type int refers to the data type of the variable being pointed by p

Initializing Pointers
Once a pointer variable has been declared, it can be made to point to a variable using
statement such as

C++ NOTES Page 4


Unit – IV

ptr_name=&var;

The above statement causes ptr_name to point to var. Now ptr_name contains the address of
var. This is known as pointer initialization. Before a pointer is initialized it should not be used.

Access the value of a variable using pointer variable

Once a pointer variable has been assigned the address of a variable, we can access the value of a
variable using the pointer. This is done by using the indirection operator(*) by writing as

*ptr_name
1) Meaning of following simple pointer declaration and definition:

int a=5;
int * ptr;
ptr=&a;
Explanation:
About variable a:
1. Name of variable : a
2. Value of variable which it keeps: 5
3. Address where it has stored in memory : 1025 (assume)
About variable ptr:
4. Name of variable : ptr
5. Value of variable which it keeps: 1025
6. Address where it has stored in memory : 5000 (assume)
Pictorial representation:

C++ NOTES Page 5


Unit – IV

C++ NOTES Page 6


Unit – IV

Pointer to class:
A pointer to a C++ class is done exactly the same way as a pointer to a structure and to
access members of a pointer to a class you use the member access operator -> operator, just as
you do with pointers to structures. Also as with all pointers, you must initialize the pointer before
using it.

Let us try the following example to understand the concept of pointer to a class:

#include <iostream>

using namespace std;

class Box {
public:
// Constructor definition
Box(double l = 2.0, double b = 2.0, double h = 2.0) {
cout <<"Constructor called." << endl;
length = l;
breadth = b;
height = h;
}

double Volume() {
return length * breadth * height;
}

private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};

int main(void) {
Box Box1(3.3, 1.2, 1.5); // Declare box1
Box Box2(8.5, 6.0, 2.0); // Declare box2
Box *ptrBox; // Declare pointer to a class.

// Save the address of first object


ptrBox = &Box1;

// Now try to access a member using member access operator


cout << "Volume of Box1: " << ptrBox->Volume() << endl;
C++ NOTES Page 7
Unit – IV

// Save the address of second object


ptrBox = &Box2;

// Now try to access a member using member access operator


cout << "Volume of Box2: " << ptrBox->Volume() << endl;

return 0;
}

Pointer to Object:
The object pointers are declared by placing in front of a object pointer's name. It takes the
following general form :

class-name ∗ object-pointer ;

where class-name is the name of an already defined class and object-pointer is the pointer
to an object of this class type. For example, to declare optr as an object pointer of Sample class
type, we shall write

Sample ∗optr ;

where Sample is already defined class. When accessing members of a class using an
object pointer, the arrow operator (->) is used instead of dot operator.

The following program illustrates how to access an object given a pointer to it. This C++
program illustrates the use of object pointer

#include<iostream.h>
#include<conio.h>
class Time
{
short int hh, mm, ss;
public:
Time()
{
hh = mm = ss = 0;
}
void getdata(int i, int j, int k)
{
hh = i;

C++ NOTES Page 8


Unit – IV

mm = j;
ss = k;
}
void prndata(void)
{
cout<<"\nTime is "<<hh<<":"<<mm<<":"<<ss<<"\n";
}
};
void main()
{
clrscr();
Time T1, *tptr;
cout<<"Initializing data members using the object, with values 12, 22, 11\n";
T1.getdata(12,22,11);
cout<<"Printing members using the object ";
T1.prndata();
tptr = &T1;
cout<<"Printing members using the object pointer ";
tptr->prndata();
cout<<"\nInitializing data members using the object pointer, with values 15, 10, 16\n";
tptr->getdata(15, 10, 16);
cout<<"printing members using the object ";
T1.prndata();
cout<<"Printing members using the object pointer ";
tptr->prndata();
getch();
}

this pointer:
Every object in C++ has access to its own address through an important pointer
called this pointer. The this pointer is an implicit parameter to all member functions. Therefore,
inside a member function, this may be used to refer to the invoking object.

Friend functions do not have a this pointer, because friends are not members of a class.
Only member functions have a this pointer.

C++ NOTES Page 9


Unit – IV

Ex:-

#include <iostream>
using namespace std;
class Box {
public:
// Constructor definition
Box(double l = 2.0, double b = 2.0, double h = 2.0) {
cout <<"Constructor called." << endl;
length = l;
breadth = b;
height = h;
}

double Volume() {
return length * breadth * height;
}

int compare(Box box) {


return this->Volume() > box.Volume();
}

private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};

int main(void) {
Box Box1(3.3, 1.2, 1.5); // Declare box1
Box Box2(8.5, 6.0, 2.0); // Declare box2

if(Box1.compare(Box2)) {
cout << "Box2 is smaller than Box1" <<endl;
} else {
cout << "Box2 is equal to or larger than Box1" <<endl;
}

return 0;
}

C++ NOTES Page 10


Unit – IV

Pointer to Derived Class and Base Class:


It is possible to declare a pointer that points to the base class as well as the derived class.
One pointer can point to different classes. For example, X is a base class and Y is a derived
class. The pointer pointing to X can also point to Y.

Ex:
#include<iostream.h>
class A
{
public:
int b;
void display()
{
cout<<"b="<<b<<"\n";
}
};
class B:public A
{
public:
int d;
void display()
{
cout<<"B= "<<b<<"\n<<" d="<<d<<"\n";
}
};
int main()
{
A *cp;
A base;
cp = &base;
cp -> b =100;
//cp -> d=200; Not Accessible
cout<<"\n cp points to the base object \n";
cp->display();
B b;
cout<<"\n cp points to the derived class\n";
cp=&b;
cp->b=150;
//cp->d=300; Not accessbile
cp->display();
return 0;
}

C++ NOTES Page 11


Unit – IV

In the above example, A and B are two classes with a one-integer member variable and
member function. The class B is derived from class A. The pointer cp points to the class A.
The variable base is an object of the class A. The address of object base is assigned to pointer
cp. The pointer cp can access the member variable b, a member of the base class, but cannot
access the variable d, a member of the derived class.

Binding in C++
Binding refers to the process that is to be used for converting functions and variables into
machine language addresses.

Static vs. Dynamic Binding.


- Static binding is done at compile time when a function is called in order to match it with the
definition.
- Dynamic binding is at run time where we can specify that the compiler matches a function call
with the correct function definition at run time.
- Virtual keyword is used if the function needs to be dynamically bounded.

Static vs. Dynamic Binding


- Binding means connecting the function call to a function implementation.
- Connecting the function call to the function implementation before execution is static binding
whereas connection them at the run-time is dynamic binding.

Comparison chart:

BASIS FOR
STATIC BINDING DYNAMIC BINDING
COMPARISON

Event Occurrence Events occur at compile time are Events occur at run time are
"Static Binding". "Dynamic Binding".

Information All information needed to call a All information need to call a


function is known at compile time. function come to know at run
time.

Advantage Efficiency. Flexibility.

C++ NOTES Page 12


Unit – IV

BASIS FOR
STATIC BINDING DYNAMIC BINDING
COMPARISON

Time Fast execution. Slow execution.

Alternate name Early Binding. Late Binding.

Example overloaded function call, Virtual function in C++,


overloaded operators. overridden methods in java.

Virtual Functions:
Virtual of functions of base class should be redefined in the derived classes. The
programmer can define a virtual function in a base class, and can then use the same function
name in any derived class, even if the number and type of arguments are matching. The
matching function overrides the base class function of a similar name. Virtual functions can only
be member functions.

We can also declare the functions as given below:

int Base::get(int) and int Derved::int get(int) even when they are not virtual.

The base class version is available to derived class objects via scope override. If they are
virtual, only the function associated with the actual type of the object is available. With virtual
functions, we cannot alter just the function type. It is illegal, therefore, to redefine a virtual
function so that it varies only in the return type. If two functions with a similar name have
different arguments, c++ compiler consider them different, and the virtual function mechanism
is dropped.

Ex:-

#include<iostream.h>
class A
{
public:
int b;
A()

C++ NOTES Page 13


Unit – IV

{
b=10;
}
virtual void display()
{
cout<<"b="<<b<<"\n";
}
};
class B:public A
{
public:
int d;
B()
{
d=20;
}
void display()
{
cout<<"D="<<d<<"\n";
}
};
int main()
{
A *cp;
A base;
cp = &base;
cout<<"\n cp points to the base object \n";
cp->display();
B b;
cout<<"\n cp points to the derived class\n";
cp=&b;
cp->display();
return 0;
}

Rules for Virtual Functions:

 The virtual function should not be static and must be a member of a class.
 The virtual function may be declared as a friend for another class. ...
 A constructor cannot be declared as virtual, but a destructor can be declared as virtual.
 The virtual function should be defined in the public section of the class. It is also possible
to define the virtual function outside the class. In such a case, the declaration is done

C++ NOTES Page 14


Unit – IV

inside the class, and the definition is outside the class. The virtual keyword is used in the
declaration and not in the function declarator.
 It is also possible to return a value from virtual functions similar to other functions.
 The prototype of the virtual function in the base class and derived class should be exactly
the same. In case of a mismatch, the compiler neglects the virtual function mechanism
and treats these functions as overloaded functions.
 Arithmetic operations cannot be used with base class pointers.
 If a base class contains a virtual function and if the same function is not redefined in the
derived classes, in such a case, the base class function is invoked.
 The operator keyword used for operator overloading also supports the virtual mechanism.

Virtual Destructor:
Deleting a derived class object using a pointer to a base class that has a non-virtual
destructor results in undefined behavior. To correct this situation, the base class should be
defined with a virtual destructor.
For example, following program results in undefined behavior. Although the output of
following program may be different on different compilers, when compiled using Dev-CPP, it
prints following.
Constructing base
Constructing derived
Destructing base

// A program without virtual destructor causing undefined behavior


#include<iostream>
using namespace std;
class base {
public:
base()
{ cout<<"Constructing base \n"; }
~base()
{ cout<<"Destructing base \n"; }
};

class derived: public base {


public:
derived()
{ cout<<"Constructing derived \n"; }
~derived()
{ cout<<"Destructing derived \n"; }
};

int main(void)
{

C++ NOTES Page 15


Unit – IV

derived *d = new derived();


base *b = d;
delete b;
getchar();
return 0;
}

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. For example,
following program prints:
Constructing base
Constructing derived
Destructing derived
Destructing base

// A program with virtual destructor


#include<iostream>
using namespace std;
class base {
public:
base()
{ cout<<"Constructing base \n"; }
virtual ~base()
{ cout<<"Destructing base \n"; }
};

class derived: public base {


public:
derived()
{ cout<<"Constructing derived \n"; }
~derived()
{ cout<<"Destructing derived \n"; }
};

int main(void)
{
derived *d = new derived();
base *b = d;
delete b;
getchar();
return 0;
}

C++ NOTES Page 16

You might also like