CS Electrical And Electronics
@cselectricalandelectronics

Explain pointers to object in Cpp?

All QuestionsCategory: Cpp LanguageExplain pointers to object in Cpp?
CS Electrical And Electronics Staff asked 4 years ago

I need short information.

1 Answers
CS Electrical And Electronics Staff answered 4 years ago

Pointers to object

  1. A pointer can point to an object created by a class.
  2. Object pointers are useful in creating objects at run time. With this the object pointers can access the public members of an object.
  3. Pointers can be used to dynamically create objects and allocate memory.
  4. 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