Bob Joe
Bob Joe

Reputation: 27

C++ Invalid New Expression Of Abstract Class Type

I get this error when using c++. I tried other solutions such as using a shared pointer but with no avail. Here is my code :

Main.cpp:

int main() {
    game_init();
    cout << items.at(0).name << endl; 
    while(true) game_tick();
    return 0;
}

Item.h:

#ifndef ITEM_H
#define ITEM_H
#include "../Rooms/Room.h"
#include <string>
#include <vector>
#include <memory>
using namespace std;

class Item {
    public :
        Room location;
        string name, desc;
        //Item(string, string, Room);
        virtual void use() = 0; 
        
};
vector <Item> items;

/*
Item::Item(string in_name, string in_desc, Room in_location) {
    name = in_name;
    desc = in_desc;
    location = in_location;
    
}*/
#endif

Items.h:

#ifndef ITEMS_H
#define ITEMS_H
#include "OldKey.h"

#include <memory>
#include <vector>

vector <shared_ptr<Item>> all_items;
OldKey   old_key;

void items_init() {
    items.push_back(old_key);
}
#endif

The error is Invalid New Expression of Abstract class Type "Item". Hope I can fix this, keep in mind I am new to c++ so please try to explain the solution or workaround simply, thanks.

Upvotes: 0

Views: 4112

Answers (1)

Daniel Junglas
Daniel Junglas

Reputation: 5930

You are trying to instantiate a class (Item) with a pure virtual function (use). This is not allowed. To fix this you could

  • Create a subclass that implements the use function and then instantiate that subclass instead of Item.
  • Make the function virtual but not pure virtual, i.e., remove the = 0 and then provide a default implementation in the Item class. A subclass can then provide its own implementation of use by overriding the function.

Note that your definition of vector<Item> items looks fishy. If you attempt to store a subclass of Item in this vector then this will be converted to an instance of Item and all information of the subclass will be lost. You may want to change this to a vector of pointers, for example.

Upvotes: 2

Related Questions