Search code examples
c++templatesinheritancepolymorphismpure-virtual

Cannot declare variable 'x' to be of abstract type 'Queue<int>'


I am building a Queue class that is inherited from an abstract class and when I was testing my constructor i kept falling on this error and I can't understand why:

"Cannot declare variable 'x' to be of abstract type 'Queue'"

"because the following virtual functions are pure within 'Queue' "

"void Abstractclass::pop() [Elem=int]"

MAIN.CPP:

#include "abstractclass.h"
#include "queue.h"
#include "stack.h"
#include <iostream>
#include <conio.h>
using namespace std;

int main()
{

Queue<int> x(10);


getch();

return 0;
}

ABSTRACTCLASS.H:

#ifndef ABSTRACTCLASS_H
#define ABSTRACTCLASS_H
#include <iostream>

using namespace std;

template <class Elem>
class Abstractclass
{
    public:
    Abstractclass();
    virtual ~Abstractclass();
    virtual void pop()=0;
};

#endif // ABSTRACTCLASS_H

QUEUE.H:

#ifndef QUEUE_H
#define QUEUE_H
#include "abstractclass.h"

template <class Elem>
class Queue: public Abstractclass <Elem>
{
    public:
        Queue(int);
       ~Queue();
        void Pop(const Elem &item);
    private:
        Elem *data;
        const int maxsize;
        int firstdata;
        int lastdata;
        int queuesize;
};

#endif // QUEUE_H

Solution

  • In class Queue:

    virtual void pop( );
    

    And spell it pop, not Pop, will fix it. c++ is case sensitive.

    I'm not sure why your error message, (different compiler?), but it should have been:

      error: 'void Abstractclass<Elem>::pop(void)': is abstract
    

    I take it your linker says: 'undefined reference to...' So the fix compiles fine but you have no definitions to link to, like:

    Abstractclass() { }
    virtual ~Abstractclass() { }
    

    and:

    Queue (int)
        :maxsize( 2 )
    { }
    ~Queue() { }
    virtual void pop( ) { }
    

    And note you have to initialize maxsize as it is declared constant

    ( I should have posted this here origanaly as I can't mark down comments)