Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ "Cannot declare parameter to be of abstract type

I'm trying to implement generic wrapper in C++ that will be able to compare two things. I've done it as follows:

template <class T>
class GameNode {
    public:
        //constructor
        GameNode( T value )
            : myValue( value )
        { }

        //return this node's value
        T getValue() {
            return myValue;
        }

        //ABSTRACT
        //overload greater than operator for comparison of GameNodes
        virtual bool operator>( const GameNode<T> other ) = 0;

        //ABSTRACT
        //overload less than operator for comparison of GameNodes
        virtual bool operator<( const GameNode<T> other ) = 0;

    private:
        //value to hold in this node
        T myValue;
};

It would seem to be I can't overload the '<' and '>' operators in this way, so I'm wondering what I can do to get around this.

like image 995
Ed L Avatar asked Oct 01 '12 02:10

Ed L


2 Answers

Your operator functions are accepting their arguments by copy. However, a new instance of GameNode can not be constructed because of the pure virtual functions. You probably want to accept those arguments by reference instead.

like image 110
Tom W Avatar answered Nov 05 '22 15:11

Tom W


Abstract types are only useful because they are polymorphic, and in fact they MUST be used polymorphically (this is the difference between virtual and pure virtual aka abstract).

Polymorphism requires a reference or pointer. You want a reference in this case.

Passing by value tries to create a new object by copying the argument, but creating an instance of an abstract type isn't possible. Passing by reference uses the existing instance instead of creating a new one, and avoids this problem.

like image 32
Ben Voigt Avatar answered Nov 05 '22 15:11

Ben Voigt