Sign in to follow this  
assainator

C++ pointer comparisation

Recommended Posts

heey all, I have a array with pointers to classes in C++:
Object **Objects;
*Objects = new Object[128];
now I would like to compare a Object with a pointer in the array.
Object obj;
for(unsigned int i = 0; i < 128; i++)
{
  if(*Objects[i] == obj)
  {
    printf("I found it!");
  }
}
the error I get is: error C2678: binary '==' : no operator found which takes a left-hand operand of type 'Texture' (or there is no acceptable conversion) And I don't really understand why it's not working since it only need's to compare 2 of the same classes. Can anyone see my mistake? thanks in advance, assainator

Share this post


Link to post
Share on other sites
By default, you cannot compare C++ classes or structures. You will need to write a custom overload of operator==() to handle your class. Does Texture have such an overload?

Off topic, why are you using pointers if your array is of fixed length? You can just use:

Object Objects[128];

Object obj;

for(unsigned int i = 0; i < 128; i++)
{
if(Objects[i] == obj)
{
printf("I found it!");
}
}


In general, if the number of elements is not fixed, consider using std::vector<> rather than using new[] and delete[].

Share this post


Link to post
Share on other sites
Your going to need to create an overloaded operator function inside your Object class that does the comparison check for you. So for example something of this nature:

bool operator ==(const Obj& obj1, const Obj& obj2);

And now you can make the comparison do whatever you want it to do.

Share this post


Link to post
Share on other sites
You have to tell the compiler how to compare your objects. This is done by overloading the == operator. For example

class Texture {
friend bool operator==( Texture const& lhs, Texture const& rhs ) {
// Make whatever comparison makes sense
return lhs.m_name == rhs.m_name;
}

private:
std::string m_name;
};



Btw. this has nothing to do with using pointers or not, it's just the way C++ works for any type.

Share this post


Link to post
Share on other sites
Not related to the original post, but... I would suggest using std::vector rather than dynamic arrays. There are very few cases where you need to use c-style arrays in C++.

Just a thought.

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