jorgen
jorgen

Reputation: 3593

Vector of objects from different classes

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?

Upvotes: 0

Views: 135

Answers (2)

psliwa
psliwa

Reputation: 1092

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().

Upvotes: 1

eerorika
eerorika

Reputation: 238301

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.

Upvotes: 3

Related Questions