Hi
I have this problem: To use "object = new class" stuff, the 'object' has to be a pointer. And that makes it an array. I don't want an array. How do I go about this?
Thanks
Printable View
Hi
I have this problem: To use "object = new class" stuff, the 'object' has to be a pointer. And that makes it an array. I don't want an array. How do I go about this?
Thanks
it makes an array?
let's say you had a pointer pXYZ
now pXYZ points to one valid objectCode:Object* pXYZ = new Object
This is where you are confused. The identifier 'array' is a const pointer to the first member of the array, array[ 0 ]. This does not mean that a pointer always points to an array, it simply points to an address in memory. If we make 'pointer' point to single we have a pointer to a single object, like so:Code:Object single; //single object
Object* pointer; //pointer to an object, not specified yet
Object array[ 10 ]; //array of objects
Code:pointer = &single;
int * first = new int;
first is a pointer to a single int
int * second = new int[6];
second is a pointer to the first element of an array of 6 ints. This is essentially the same description as the name of an array. The name of an array acts as a constant pointer to the first element of the arry. second can be used anywhere the name of an array can be used.
const SIZE = 8;
int third[SIZE];
void display(int * array, int size)
{
for(i = 0; i < size; i++)
cout << array[i] << endl;
}
display(second, 6);
display(third, SIZE);
Okay, thanks...
That means I should use pointers whenever I can? You know, to save memory?
>> That means I should use pointers whenever I can? You know, to save memory?
Only use pointers if they are necessary. If the use of pointers in a program would drastically increase it's efficiency, then by all means, use them.
But then why not use them?
pointer = &single ... why the reference?Quote:
Originally posted by endo
This is where you are confused. The identifier 'array' is a const pointer to the first member of the array, array[ 0 ]. This does not mean that a pointer always points to an array, it simply points to an address in memory. If we make 'pointer' point to single we have a pointer to a single object, like so:Code:Object single; //single object
Object* pointer; //pointer to an object, not specified yet
Object array[ 10 ]; //array of objects
Code:pointer = &single;