Class Question

Started by
11 comments, last by Esap1 23 years, 10 months ago
Um, what? Map_class is a class, Im trying to make an array of Object_class''s, of that *Object pointer. Can I do it that way?
Advertisement
Anyone???
I've been away for a little while.


OK, when you use pointers, they are really just another type of variable, and when you do this:


void function(int* pointer)
{
// do something here
}

void main()
{
int* pointer;

function(pointer);
}



function() just makes a copy of the pointer variable and uses that. So to solve your problem, you don't need to change anything except this one line:


int LoadFile(char *file,Object_class *&Object)



Which basically just tells the compiler not to make a copy of the pointer. Simple, huh? (In reality, it does the double-pointer thing in the compiled code, but you use it like a single pointer.)


OK, now with your objects, you need a constructor to assign a value to a data member. As your code is now, you can't access the member from outside the class member functions, because that's the default with classes. If you do want to access it from outside, use public:. I've modified the code with all of those changes, and here is the finished product:


class Object_class {
public:
int hi;
Object_class();
};

Object_class::Object_class()
{
// this function is called whenever an Object_class is created

hi = 0; // default value of hi
}

int LoadFile(char *file, Object_class *&Object)
{
Object = new Object(10); // should be brackets
}

void Whatever()
{
Object_class *Object;
LoadFile("hi.txt", Object);
}



And yes, an array variable is really just a pointer to the first element anyway. You can do this:


void main()
{
char* mystring = new char[10];
}



And you can do the same thing with an Object_class pointer and an Object_class array.


Here's the Map_class code again:


class Map_class {
Object_class *Object;
void LoadFile(char *file);
};

void Map_class::LoadFile(char *file)
{
Object = new Object_class[numObject];
//Load in the stuff
}



BTW, I was reading up on the sizeof() operator, and it says that it returns the size of an array, so there's really no point in storing the size in your map class. I think that this should work:


void main()
{
Object_class* p = new Object_class[10];

int numObjects = sizeof(p); // should be 10
}



That code shouldn't cause anymore performance slowdown than just storing the size of the array yourself, because sizeof() just looks up the variables that C++ is already using to track the size of the array.




- null_pointer
Sabre Multimedia


(I wish the source tags would work properly!)


Edited by - null_pointer on June 18, 2000 7:24:04 AM

This topic is closed to new replies.

Advertisement