1 Answers
Pointers to object
- A pointer can point to an object created by a class.
- Object pointers are useful in creating objects at run time. With this the object pointers can access the public members of an object.
- Pointers can be used to dynamically create objects and allocate memory.
- We can also create an array of objects using pointers using the new operator.
Example:
#include <iostream>
using namespace std;
class item
{
int code;
float price;
public:
void getdata(int a, float b)
{
code = a;
price = b;
}
void show(void)
{
cout<<“code:”<<code<<“\n”;
cout<<“price:”<<price<<“\n”;
}
};
int main()
{
item x;
item *ptr = &x;
//Two ways of accessing the member functions
x.getdata(200, 42.33);
x.show();
ptr->getdata(300,34.45);
ptr->show();
(*ptr).show();
return 0;
}
Output:
code:200
price:42.33
code:300
price:34.45
code:300
price:34.45