Loading....
Coupon Accepted Successfully!

 

Pointer To Class

We know that a pointer is a variable that holds the address of another data variable. The variable may be of any data type, that is, int, float, or double. In the same way, we can also define pointer to class. Here, the starting address of the member variables can be accessed. Thus, such pointers are called class pointers.
 

Example:

class book

{char name [25];

char author [25];

int pages;

};

(a) class book *ptr;

or

struct book *ptr;


In the above example,
*ptr is a pointer to a class book. Both statements (a) and (b) are valid. The syntax for using pointers with members is as given below.
 

1) ptr->name 2) ptr->author 3) ptr->pages.


By executing these three statements, the starting address of each member can be estimated.

 

13.10 Write a program declares a class. Declare pointer to class. Initialize and display the contents of the class member.

#include<iostream.h>

#include<conio.h>

void main()

{

class man

{

public :

char name[10];

int age;

};

man m={“RAVINDRA”, 15};

man *ptr;

ptr=&(man)m;

// *ptr=(man)m;

// *ptr=man(m);

// *ptr=m;

// ptr=&m;

clrscr();

cout<<“\n” <<m.name <<“ ”<<m.age;

cout<<“\n”<<ptr->name<<“ ”<<ptr->age;

}

OUTPUT

RAVINDRA 15

RAVINDRA 15


Explanation:
In the above program, the pointer ptr points to the object m. The statement ptr = &(man) m assigns the address of the first member element of the class to the pointer ptr. Using the dot operator and arrow operator, contents can be displayed. The display of the class contents is possible, because the class variables are declared as public. The below given statements can also be used to assign the address of the object to the pointer.
 

ptr=&(man)m;

*ptr=(man)m;

*ptr=man(m);

*ptr=m;

ptr=&m;





Test Your Skills Now!
Take a Quiz now
Reviewer Name