I have a hierarchy of Figure
as base class and several sub classes Circle
, Square
, ecc. I want to overload <
operator in Figure
to sort Figures by eg. Surface
which is implemented in base classes.
This is my code:
//Figure.hpp
class Figure
{
public:
virtual float surface() const = 0;
virtual float perimeter() const = 0;
friend bool operator<(const Figure& lhs, const Figure& rhs);
friend bool operator>=(const Figure& lhs, const Figure& rhs);
}
//Figure.cpp
bool operator<(const Figure& lhs, const Figure& rhs)
{
return lhs.surface() < rhs.surface();
}
bool operator>=(const Figure& lhs, const Figure& rhs)
{
return lhs.surface() >= rhs.surface();
}
//Square.hpp
class Square : public Figure{
public:
Square(float size);
float surface() const{
return mSize * mSize;
};
float perimeter()const{
return mSize * 4;
}
private:
float mSize;
};
Problem is I get an error at runtime:
libc++abi.dylib: Pure virtual function called!
at lhs.surface()
.
I call the <
operator in a LinkedList
with Template
:
template <typename T>
void List<T>::insertNewNode(T& dataIn)
{
if(isEmpty())
{
insertBegin(dataIn);
}else //otherwise
{
if(dataIn < *startPtr->data)
{
insertBegin(dataIn);
}
else if(dataIn >= *endPtr->data) /
{
insertEnd(dataIn);
}
else
{
//...
}
}
}
//main.cpp
List<Figure> *list = new List<Figure>();
Figure *square = new Square(46);
list->insertNewNode(*square);
EDIT https://github.com/sanandrea/GenericLinkedList
Is this feasible or I am doing everything wrong?