vector in an abstract class

Dec 8, 2019 at 9:56pm
Let's say I create a vector inside an abstract class. How would I be able to use .pushback() from another class if I can't initialise an object of an abstract class?

Obviously the easiest solution is to put the vector in another class but I need another way.

Dec 8, 2019 at 10:17pm
are you trying to push back a class object or use a vector from another class? .push_back() is a class member of vector, im not sure i understand what you mean by using it from another class.
Dec 8, 2019 at 10:25pm
For example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

class car
{

protected:
int distance;

virtual void mileage (int c, int d) = 0;

public:

vector <miles> mile;
};

class miles
{
//some function
int d = 500;
//how to pushback int d to the vector in the class 'car'? 
//as you cannot create an object of an abstract class?
};
Dec 8, 2019 at 10:35pm
You could make a getter function and push it back into the vector.

something like:

1
2
3
4
car c;
miles m;

c.mile.push_back(m.GetD());


Although c class object is of abstract type so you cant do exactly what I wrote but you get the idea.
Last edited on Dec 8, 2019 at 10:41pm
Dec 8, 2019 at 10:43pm
That's what I thought but the fact that you can't create an object of an abstract class throws me off as I would have normally done just as you said.

Is there any way to actually do it?
Dec 8, 2019 at 10:53pm
probably by creating a vector of pointers to the abstract class type, because as you said, you can't create an object of an abstract class. I have little experience with using abstract classes and even less with pointers, but im sure someone will correct me if im wrong.
Last edited on Dec 8, 2019 at 10:55pm
Dec 9, 2019 at 5:05pm
It's meaningless to try and push back a number to an object of type car, because such an object can't exist. If you've made car abstract, you're saying you never want to have anything that's just a generic car, so why would you ever need to push a value to the vector of such a thing?

If you're manipulating objects of type car, when that must mean you're manipulating objects of specialised types derived from car, in which case you have an object that you can actually instantiate.

So... I don't understand why there's a problem at all?
Last edited on Dec 9, 2019 at 5:06pm
Topic archived. No new replies allowed.