Professional Documents
Culture Documents
C++ Pointers - 2
Sruthi M.
Assistant Professor, Department of ECE
Vidya Academy of Science and Technology, Thrissur
Ref: Object Oriented Programming using C++ and JAVA, E. Balaguruswamy, Mc Graw Hill
Education
Sruthi M, ECE
Pointer Arithmetic
• Perform arithmetic operations on a pointer just as a
numeric value
• Four arithmetic operators that can be used on
pointers: ++, --, +, and –
• Example:
– int a[10] ;
– int *ptr;
– ptr = &a[0]; // ptr refers to base address of variable a
– ptr++; or ++ptr // incrementing pointer
– ptr--; or –ptr // decrementing pointer
Sruthi M, ECE
Array of Pointers
• Points to an array of data items.
• Declaration –
• Int *inarray[10]; //declares an array of 10
pointers, each points to an integer.
• Address of first pointer is inarray[0];
• Address of final pointer is inarray[9];
Sruthi M, ECE
Sample program
• #include <iostream> • // take the value using pptr
• using namespace std; • cout << "Value of var :" <<
• int main () { var << endl;
• int var; • cout << "Value available at
• int *ptr; *ptr :" << *ptr << endl;
• int **pptr; • cout << "Value available at
• var = 3000; **pptr :" << **pptr << endl;
• // take the address of var
• ptr = &var;
• // take the address of ptr using
• return 0;
address of operator & • }
• pptr = &ptr;
Sruthi M, ECE
Pointer to Objects
• A pointer can point to an object created by a class.
• Let item is a class and x is an object defined,
• item x;
• pointer ptr of type item is defined as:
• item *ptr =&x;
• Object pointers are used to access the public members of an object
• 2 methods of referring member functions
– x.getdata(); (using dot operator and object)
– x.show();
– Or
This Pointer
• Every object in C++ has access to its own
address through an important pointer
called this pointer.
• Friend functions do not have a this pointer,
because friends are not members of a class.
Only member functions have a this pointer.
Sruthi M, ECE
Sample Program
•
•
#include <iostream>
using namespace std;
• int main(){
• class Demo { • Demo obj;
• private:
• int num; • obj.setMyValues(100,
• char ch;
• public: 'A');
•
•
void setMyValues(int num, char ch){
this->num =num;
• obj.displayMyValues();
• this->ch=ch; • return 0;
• }
• void displayMyValues(){ • }
• cout<<num<<endl;
• cout<<ch;
• }
• };
Sruthi M, ECE
Sample Program
• #include <iostream> • int main ()
• using namespace std; {
class Base Base B1;
{ Base *ptr;
public: ptr = &B1;
int x; ptr->x = 10;
void display () ptr->display();
{ Derive D1;
cout<<”X=”<<x<<endl; Derive *ptr1;
} ptr1 = &D1;
}; ptr1->x = 10;
class Derive: public Base ptr1->y = 20;
{ ptr1->display ();
public: }
int y;
void display ();
{
cout<<”X=”<<x<<endl;
cout<<”Y=”<<y<<endl;
}
};
Sruthi M, ECE