Pointer
Pointer
Written by
Unit Outcome 1 : Create C++
programs to perform the given
arithmetic operations using
pointers
Written by
Learning Outcome 1 : student will be
able to use pointers.
Written by
What we will learn today
Pointer
Declaration
Working Of
Pointer Pointer
Initialization
Pointer
Memory
Allocation Operation
on Pointer
► Every variable is a memory location and every memory location has its address defined
► Address can be accessed using ampersand (&) operator which denotes an address
► C++ tasks are performed more easily with pointers
► C++ tasks, such as dynamic memory allocation, cannot be performed without them
► Pointer is a variable in C++ that holds the address of another variable.
► Pointers have data type just like variables.
► Pointers are variables which display value at the memory address.
► Like any variable or constant, you must declare a pointer before you can work with it
7
► Declaring Pointers
► Syntax:
data_type *pointer_name;
int *ptr; //declaration
8
ptr=&a; //initialization
Pointer Operator
#include<iostream.h>
void main()
{ ptr a
int a=10;
int *ptr; Value of ptr 1024 10
ptr=&a; 1000 1024
cout<<"\n Value of a:"<<a; //a=10 Value of a
► Operation
► Increment operator (++)
► Decrement operator (–)
► Addition (+)
► Subtraction (-)
► Valid statements
► p2-p1;
► ptr1+1;
► ptr=ptr+2;
► Invalid statements
► p1+p2;
► p2 * p1;
► p2/p1;
Page 11 Maharashtra State Board of Technical Education 4 July 2020
Pointer Arithmetic
Program code
Output
Pointer to
Object Pointee derived
class
► C++ uses a unique keyword called ‘this’ to represent an object that invokes a
member function.
► This unique pointer is automatically passed to a member function when it is invoked.
► ‘this’ is a pointer that always point to the object for which the member function was
called.
► The ‘this’ pointer can be treated like any other pointer to an object.
► For example, the function call
20
A.max () will set the pointer ‘this’ to the address of the object A.
Next time suppose we call B.max(), the pointer ‘this’ will store address of object B.
If we try to write
x=x;
It will give garbage Value
Output :
Page 22
to D. Maharashtra State Board of Technical Education 4 July 2020
Pointers to derived class
► Example:
B *cptr; // pointer to B class
B b; //Base object
D d; // Derived object
cptr=&b; //ptr points to object b
Output :