Pointer: Pointer to Objects: Using Dot Operator, Using Arrow Operator and Object Pointer

Doorsteptutor material for IAS is prepared by world's top subject experts: fully solved questions with step-by-step explanation- practice your way to success.

Download PDF of This Page (Size: 254K)

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 run.

public:

int marks;

void get data ().

void put data ().

};

void student: get data ()

{

cin >> name.

cin >> run.

cin >> marks.

}

void student: put data ()

{

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

cout << “Roll no” << run << “\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.

Using Dot Operator

st. marks = 90.

st. get data ().

Using Arrow Operator and Object Pointer

ptr marks = 90.

ptr get data ().

another way to represent is (*ptr)

(*ptr). marks = 90.

(*ptr). get data ();

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 run.

public:

void get data ()

{

cin >> this -> run.

}

void put data ()

{

cout << this -> run.

};

void main ()

{

ABC A, B.

A. get data ().

A. put data ().

B. get data ().

B. put data ().

}

  • When a get data () or put data () function is called through object A, this has the address of object A.

  • Similarly, when a get data () or put data () function is called through object B, this has the address of object B.

Developed by: