Pointer to Object:-
An object of a class behaves identically as any other variable. Just as pointers can be defined in case of base C++ variables so also pointers can be defined for an object type. To create a pointer variable for the following class
{
int code;
char name [20] ;
public:
inline void getdata ( )= 0 ;
inline void display ( )= 0 ;
The following codes is written employee *abc;
This declaration creates a pointer variable abc that can point to any object of employee type.
Pointers to Objects: Pointers to objects are useful for creating objects at run time. To access members
arrow operator ( ) and de referencing operator or indirection (*) are used.
Declaration of pointer.
Example:
Here obj is a pointer to object of type item.
class item
{
public:
int code;
void getdata(int a,float b)
{
code=a;
}
void show()
{
cout<<”code:”<<code<<”\n”<<”Price:”<<price<<endl;
}
};
Declaration of object and pointer to class item:
item *ptr=&obj;
The member can be accessed as follow.
a)Accessing members using dot operator obj.getdata(101,77.7); obj.show();
b)using pointer
ptr->getdata(101,77.7); ptr->show();
c)Using de referencing operator and dot operator (*ptr).getdata(101,77.7);
(*ptr).show();
Creating array of objects using pointer:
item *ptr=new item[10];
Above declaration creates memory space for an array of 10 objects of type item.
Program:
#include<conio.h>
class item
{
public:
int code;
void getdata(int a,float b)
{
code=a;
}
void show()
{
cout<<code<<"\t"<<price<<endl;
}
};
int main()
{
int n;
int cd;
float pri;
cout<<"Enter number of objects to be created:";
cin>>n;
item *ptr=new item[n];
item *p;
p=ptr;
for(int i=0;i<n;i++)
{
cout<<"Enter data for object"<<i+1;
cout<<"\nEnter Code:";
cin>>cd;
cout<<"Enter price:";
cin>>pri;
p->getdata(cd,pri);
p++;
}
p=ptr;
cout<<"Data in various objects are "<<endl;
cout<<"Sno\tCode\tPrice\n";
for(i=0;i<n;i++)
{
cout<<i+1<<"\t";
ptr->show();
ptr++;
}
return 0;
}