1

I wonder if i could store different types of non-native data into a single vector? it goes like this:

class foo
{
    private:
        int x;
    public:
        foo(int a=0):x(a){}
        int getx() { return x; }
        void setx(int a=0) { x=a; }
};
class var:public foo
{
    private:
        int y;
    public:
        var(int a=0, int b=0):foo(a), y(b){}
        int gety() { return y; }
        void sety(int a=0) { y=a; }
};
class var1:public foo
{
    private:
        int z;
    public:
        var(int a=0, int b=0):foo(a), z(b){}
        int getz() { return z; }
        void setz(int a=0) { z=a; }
};

How to declare a vector to hold data of both var and var1 types? I could store them in a std::vector<foo>, but then they'd be treated as if they are of foo types

miken32
  • 42,008
  • 16
  • 111
  • 154
  • We seem to be getting this question a lot these days. Is someone telling beginners that storing different types in one container is a good idea? – Beta May 18 '15 at 05:30
  • possible duplicate of [Vectors and polymorphism in C++](http://stackoverflow.com/questions/16126578/vectors-and-polymorphism-in-c) – Beta May 18 '15 at 05:33

2 Answers2

3

If you add a sub-type of foo to a std::vector<foo>, you will lose the sub-type information. See What is object slicing? for more info.

A std::vector<foo> container can only hold objects of type foo. To be able store objects that are derived from foo, you'll have to allocate objects on the heap and store the pointers in a vector of pointers, preferably a vector of smart pointers - std::vector<std::shared_ptr<foo>> or std::vector<std::unique_ptr<foo>>.

Community
  • 1
  • 1
R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • Ah, apparently that means i made a big mistake, or rather, the lecturers in my campus did. Either they overlooked this bit or maybe they plainly have no idea about this. This was supposed to be an exercise for class relationships. Man, i'm starting to worry about my future in programming. – Raikou UltraReloaded May 19 '15 at 15:02
  • As long as you learn from those mistakes, I wouldn't worry too much about it. – R Sahu May 19 '15 at 15:24
1

You can use polymorphism. So instead of declaring as std::vector<foo>, you declare as pointer of the base class: std::vector<foo*>.

Then in your function you can declare as

vector<foo*> bar;

bar.push_back( new var1() );
rcs
  • 6,713
  • 12
  • 53
  • 75