0

So i have this:

class Grup : public Shape
{
private:
    std::vector<Shape *> continut;
public:
    static const std::string identifier;
    Grup(){};
    ~Grup(){
    continut.clear();
    };
    void add(Shape *);
    void remove(Shape *);
    void output(std::ostream &) const;
    void readFrom(std::istream &);
    void moveBy(int, int);
    friend std::ostream &operator<<(std::ostream &, const Grup &);
}

and i want to implement the remove function. i tried this:

void Grup::remove(Shape *s)
{
vector<Shape*>::iterator it;
it = continut.begin();
while(it!=continut.end())
{
    if((*it) == s)
    {
    it = continut.erase(it);
    }
    else it++;

}
}

but the == doesn't return me a true value. i also tried to overload the operator == on each shape but same result. what can i do?

makc
  • 2,569
  • 1
  • 18
  • 28
user2116010
  • 211
  • 4
  • 7
  • 10
  • 1
    Just two advices, use [`std::remove`](http://en.cppreference.com/w/cpp/algorithm/remove) instead of a `while` (why type an algorithm wich is already typed on the stl?) and don't clear the vector in the destructor, it will be cleared anyways. – PaperBirdMaster Apr 15 '13 at 13:12
  • post your code of overloading operator== that didnt work – makc Apr 15 '13 at 14:35
  • @makc i tried something like this: `bool Triunghi::operator==(const Triunghi& T) { if(this->identifier==T.identifier&&this- >p1.getX()==T.p1.getX()&&this->p1.getY()==T.p1.getY()&&this->p2.getX()==T.p2.getX()&&this->p2.getY()==T.p2.getY()&&this->p3.getX()==T.p3.getX()&&this->p3.getY()==T.p3.getY()) return 1; return 0; }` – user2116010 Apr 15 '13 at 19:54
  • @user2116010 what does the identifier represents? Did you try debugging this code and check which parameter wasn't equal? – makc Apr 16 '13 at 08:19
  • @makc yes i tried and it didn't even enter this overload function – user2116010 Apr 16 '13 at 10:09
  • @user2116010 make sure you didn't run optimized code, this is your real problem solve the debug problem and you'll be able to figure out the overloading problem – makc Apr 16 '13 at 12:23

2 Answers2

1

This is comparing the memory addresses of two Shape objects:

if((*it) == s) // '*it' is of type `Shape*`

it is not comparing two Shape objects. A further dereference is required to use operator== defined for Shape. However, see What's the right way to overload operator== for a class hierarchy? for a discussion on how to handle operator== for a class hierarchy.

Community
  • 1
  • 1
hmjd
  • 120,187
  • 20
  • 207
  • 252
0

you are comparing the shape pointers addresses and they are different.

you should overload operator ==

here are some examples:

C++ Operator Overloading Guidelines

Operator overloading

Community
  • 1
  • 1
makc
  • 2,569
  • 1
  • 18
  • 28