1

I am currently trying to learn c++ and I am having an issue when trying to create a vector which iterates through several different objects whom all inherit from the same base class with smart pointers.

I parse a file and create the objects and insert them into the vector depending on the character parsed but I keep getting the error:

Error   C2664   'std::unique_ptr<Test *,std::default_delete<_Ty>>::unique_ptr(const std::unique_ptr<_Ty,std::default_delete<_Ty>> &)': cannot convert argument 1 from 'std::unique_ptr<Test2,std::default_delete<_Ty>>' to 'std::nullptr_t'"

Code is as follows:

class Test {
public:
    virtual ~Test(){}
    virtual int update() {}
};


class Test2 : public Test {
private:
    int a;
public:
    Test2() {

    }
    Test2(int n) {
        a = n;
    }
    int update() override {
        return a;
    }
};

class Test3 : public Test {
private:
    int a;
public:
    Test3() {

    }
    Test3(int n) {
        a = n;
    }
    int update() override {
        return a;
    }
};

class Test4 : public Test {
private:
    int a;
public:
    Test4() {

    }
    Test4(int n) {
        a = n;
    }
    int update() override {
        return a;
    }
};

class manager {
private:
    std::vector<std::unique_ptr<Test*>> vList;
    std::ifstream lvlFile;
public:
    std::string tmp;
    manager() {
    }
    ~manager() {

    }
    void init(const char *path) {

        lvlFile.open(path, 0);
        while (lvlFile.eof() != true) {
            std::getline(lvlFile, tmp);
            for (char& a : tmp) {
                switch (a) {
                    case 'w':
                        vList.emplace_back(std::make_unique<Test2>(2));
                        break;
                    case 'g':
                        vList.emplace_back(std::make_unique<Test3>(3));
                        break;
                }
            }
        }
    }
    void print() {
        for (auto& i : vList) {
            std::cout << (*i)->update() << std::endl;
        }
    }

};

manager *m;

int main() {
    m = new manager();
    m->init("lvl.txt");
    _getch();
}

Maybe I have misunderstood something crucial here but I have been looking around and found no real answers so any pointers to this would be most welcome!

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621

1 Answers1

1

Change std::vector<std::unique_ptr<Test*>> to std::vector<std::unique_ptr<Test>>.

std::unique_ptr<Test*> is a pointer to pointer (Test**).

juzzlin
  • 45,029
  • 5
  • 38
  • 50