Pointers to object

Please explain what does "item *d=p" mean here.

#include <iostream>
using namespace std;

class item{
int a,b;
public:
void getdata(int,int);
void putdata();
};

void item::getdata(int i, int j){
a=i;
b=j;
}

void item::putdata(){
cout <<"a"<<a<<endl;
cout <<"b"<<b<<endl;
}

int main(){
item *p=new item[2];
item *d=p;
int i,j,k;
for(i=0;i<2;i++){
cout <<"Enter item,price"<<endl;
cin>>j>>k;
p->getdata(j,k);
p++;
}
for(i=0;i<2;i++){
d->putdata();
d++;
}
return 0;
}


Can "p->putdata();" be used instead of "d->putdata();" ? Kindly explain
Ehm, my logic may be incorrect (pointers are my weakness) but item *d = p creates a pointer that points to p, which is a pointer that points to an array of class "items".

No you cannot use p->putdata(); because it will display the memory address of the new item[2] instead of the value. I believe that's correct.
item *p=new item[2];
p is a pointer that points to dynamically allocated memory.

item *d=p;
d is a pointer that is reassigned to p. IE: it points to the same thing p points to. Therefore d also points to the dynamically allocated memory.

p->putdata(); and d->putdata(); are both exactly the same, as both pointers point to the same thing and are thus identical.
Actually, p->putdata() is possible, considering item *p has the address for the first item of the array, just like item *d does.
When i tried compiling it, using p->putdata() it gave me junk numbers.
Last edited on
did you initialize the items with getdata() first?
1
2
3
4
5
d = p;
p->getdata(j,k);
p++; //now d!=p
d->putdata(); //d points to the beginning 
d++;

That's why you're getting garbage, and that's the purpose of d
Thanks for all the replies.I am now able to understand the difference between p->putdata(); and d->putdata();

After making a few changes , i was able to use p->putdata() instead of d->putdata()

The changes:

int main(){
item *p=new item[2];
item *d=p;
int i,j,k;
for(i=0;i<2;i++){
cout <<"Enter item,price"<<endl;
cin>>j>>k;
p->getdata(j,k);
p++;
}
for(i=0;i<2;i++){
p--;
}

for(i=0;i<2;i++){
p->putdata();
p++;
}
return 0;
}

Once again thanks for all the replies and please do help me in future too.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
item *p=new item[2];//NOW P POINTS TO THE FIRST array element
item *d=p; //u create a pointer d that also points to the same element.NOTE:d, p are two distinct entities
int i,j,k;
for(i=0;i<2;i++){
cout <<"Enter item,price"<<endl;
cin>>j>>k;
p->getdata(j,k);
p++;
}//now P points to the last array element;d still points to the 1st


for(i=0;i<2;i++){
d->putdata();//********here d points within array bounds but p goes beyond bounds of the array, so is meaningless **********
d++;
}
return 0;
}
Topic archived. No new replies allowed.