Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Question for why Pointers can't be assigned to Objects

Status
Not open for further replies.

pghsteelers

Technical User
Apr 21, 2006
121
US
Why can you declare a pointer of type <classname> and assign it to an array of objects, but you can't assign it to individual objects without assigning it to the address of the individual object?

For example:

class CSomeClass
{
...
...
...
}

...
...
...

int main()

CSomeClass objname1;
CSomeClass objarray1[3];
CSomeClass* ptest;

ptest = &objname1; //excepted
ptest = objarray1; //excepted

ptest = objname1; //not excepted

...
...
...
return 0;
}
 
Oh and I left out that when you assign the pointer to the array, you are actually assigning the pointer to the first element, which in it's own right is a separate object just residing in an array of objects.
 
Pointers can only hold pointers. It's the same as asking why you can't assign a double to an int -- they're different types.
 
So if you can only assign pointers to pointers, then where am i missing that assigning a pointer to an array follows suit?
 
An array basically is a pointer. It's a pointer to the first element in the array. When you specify an element in the array, like arr[3] you are dereferencing that pointer and doing the same kind of thing as this:
Code:
*(arr + 3)
 
Ah, thats right, thank you kindly for the break down.
 
An array name is the same thing as the address of the first element. it is a pointer value in that it can't be moved, as opposed to a pointer variable.

++objarray; // illegal

if ptest pointed to allocated space,
you could assign objname1 to it like this
*ptest = objname1;

This would make ptest hold a copy of objname1
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top