0

I'm trying to create a vector containing objects from different classes, derived from a base class. Following answers to this question I've the following code which tries four different ways (commented out below); none of which will compile:

class observable {

    public:
    virtual void observe(alglib::complex_1d_array)=0;

    observable() {

    }
};

class Energy : public observable {

    public:
    void observe(alglib::complex_1d_array);

    Energy() {

    }
};

class ObservableCollection {

    private:
    int no_obs;
    vector<observable*> obs;

    public:

    ObservableCollection(vector<string> obs) {
        no_obs=obs.size();
        for(int i=0;i<no_obs;i++) {
            if(!strcmp(obs[i].c_str(), "energy")) {
                // option 1:
                // Energy E();
                // obs.push_back(E);

                // option 2:
                // obs.push_back<std::shared_ptr<observable>(new Energy())>;

                // option 3:
                // obs.push_back(new Energy());

                // option 4:
                // observable *E=new Energy();
                // obs.push_back(E);
            }
        }
    }


};

Any ideas?

1
  • 4
    What are the compilation errors in each case? Commented Jun 21, 2015 at 19:38

2 Answers 2

3

Option 1 cannot work because obs is a vector<observable*>^. You cannot push a object of type observable because you can only store pointers (observable*) in it. You could store such objects in a vector<observable> but you cannot store Energy objects in such vector.

Option 2 cannot work because ecause obs is a vector<observable*>^. You cannot push a object of type std::shared_ptr<observable> because you can only store raw pointers (observable*) in it. To store shared pointers, the vector must be of type vector<shared_ptr<observable>>.

Option 3 is effectively same as option 4. They would work if you actually tried to push into the member variable obj. However, you've hidden that variable by declaring a local variable by the same name (the function parameter). You cannot push observable* into a vector of strings. The compilation error should be clear about this. If you inteded to push into the member variable, you can use this->obs instead, or even better, use different name for the local variable.

^Assuming you were actually pushing into this->obs rather than the local variable.

Sign up to request clarification or add additional context in comments.

Comments

1

You are passing vector obs (called the same as member) and you are trying to push your class to it. If you want to push to the member, use this.obs.push_back().

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.