NIOS Computer Science: Chapter 15 – Pointer Part 3

Download PDF of This Page (Size: 291K)

Image shows pointer to objects

Image Shows Pointer to Objects

Image shows pointer to objects

Pointer to Objects

Object pointers are useful in creating objects at run time. Object pointers can be used to access the public members of an object. Consider a class student defined as follows:

class student

{

char name [20];

int rn;

public :

int marks;

void getdata ( );

void putdata ( );

};

void student : : getdata ( )

{

cin >> name;

cin >> rn;

cin >> marks;

}

void student : : putdata ( )

{

cout << “Name” << << name << “\n”;

cout << “Roll no” << rn << “\n”;

cout << “Marks” << marks << “\n”;

}

Declare an object st and pointer ptr as follows:

student st;

student *ptr;

We can refer to the member functions and data member of student in two ways.

(I) Using Dot Operator

st.marks = 90;

st.getdata ( );

(Ii) Using Arrow Operator and Object Pointer

ptr marks = 90;

ptr getdata ( );

another way to represent is (*ptr)

(*ptr).marks = 90;

(*ptr).getdata( );

This Pointer

C++ uses a unique keyword called this to represent the object that invokes a member function. This is a pointer that points to the object for which this function was called.

For example;

class ABC

{

int rn;

public:

void getdata ( )

{

cin >> this -> rn;

}

void putdata ( )

{

cout << this -> rn;

};

void main ( )

{

ABC A, B;

A . getdata ( );

A . putdata ( );

B . getdata ( );

B . putdata ( );

}

When a getdata ( ) or putdata ( ) function is called through object A, this has the address of object A.

Similarly, when a getdata ( ) or putdata ( ) function is called through object B, this has the address of object B.