Sign in to follow this  
Niddles

Operator Overloading Problem

Recommended Posts

Hello I have a class that has an overloaded operator:
class ObjectModel
{
    public:
    ObjectModel();
    ObjectModel(string file);
    ~ObjectModel();
    ObjectModel& operator=(const ObjectModel &a)
    {
        NumVertex = a.NumVertex;
        NumNormal = a.NumNormal;
        NumTexCoord = a.NumTexCoord;
        NumTriangle = a.NumTriangle;
        VertexArray = a.VertexArray;
        NormalArray = a.NormalArray;
        TexCoordArray = a.TexCoordArray;
        TriangleArray = a.TriangleArray;
        Filename = a.Filename;
        return *this;
    }
    int NumVertex;
    int NumNormal;
    int NumTexCoord;
    int NumTriangle;
    ObjectVertex *VertexArray;
    ObjectNormal *NormalArray;
    ObjectTexCoord *TexCoordArray;
    ObjectTriangle *TriangleArray;
    string *Filename;
};

However, it is not working later when it is called:
ObjectLoader::ObjectLoader(int objects)
{
    ObjectArray = new ObjectModel[objects];
    for(int a=0; a < objects; a++)
    {
        ObjectArray[a] = NULL; //Here
    }
}
//and
...
void ObjectLoader::LoadObject(int index)
{
    if(ObjectArray[index] != NULL) FreeObject(index); //Here
    ObjectArray[index] = new ObjectModel; //Here
    ReadData(index);
}

Can someone help me weed out this problem? Thanks.

Share this post


Link to post
Share on other sites
None of these make much sense:

ObjectArray[a] = NULL;
if(ObjectArray[index] != NULL)
ObjectArray[index] = new ObjectModel;

From the looks of this:

ObjectArray = new ObjectModel[objects];

Each ObjectArray[*] is an instance of ObjectModel, not a pointer-to-ObjectModel. Value types usually have no concept of NULL, nor does it make sense to assign them to pointers to "new ObjectModel"s from the heap.

Note that your overloaded operator= only does what the default operator= does as well (e.g. assign all individual objects).

It sounds like you might want to be using:

ObjectModel** ObjectArray = new ObjectModel*[index];. This causes that code to make sense, since you're dealing with pointers to ObjectModels now, but then the ObjectModel's operator= becomes entirely unrelated.

Share this post


Link to post
Share on other sites
As MaulingMonkey You overloaded only the ascription(?! don't know how to say it correct) operator. It mean that you can do something like this:
Object a, b;
//some operations with a
b = a;

If you want to get to specific element of object you should overload [] operator too.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this