One function to fill a vector of =/ daughters class

Hi,

I am very new to C++ (and this website).

I want to create just one function which are able to fill a vector of different derived class from an abstract class

I have 4 class on this little code :

Garage which have the vector <Vehicle*> m_garageList as member type

Vehicle is an abstract mother class, she have 2 daughters : Car and Motocycle

I want to put a car or a motocycle in my Garage.

Here is how I do in my .cpp file :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
void Garage::addVehicle(Vehicle &a) //creation of a polymorphic fonction
{

m_garageList.push_back(new Vehicle(a)); 

//If I only do this I fill my vector with Vehicle and not with Car or Motocycle

int last (0);
last = m_garageList.size() - 1; 

//These two previous line was to get the number of the last vector member 


m_garageList[last] = &a;

//I replace my Vehicle with the real Car or Motocycle object

}


I am a beginner with C++, I am aware that this code could be not the best code at all.

Without surprise I have the error : invalid new-expression of abstract class type 'Vehicle'


So the question is :

How can I create a working function who fill vector with different daughters class object which from a abstract mother class ?
Last edited on
1
2
3
4
void Garage::addVehicle(Vehicle& a)
{
	m_garageList.push_back(&a);
}


Note that doing it this way the objects that you pass to addVehicle must stay alive for as long as the Garage is alive otherwise you end up with dangling pointers (i.e. invalid pointers that points to objects that no longer exist).
Last edited on
Just for more info:

You can't create an object of type Vehicle because you have Vehicle as an abstract base class (ABC).
https://isocpp.org/wiki/faq/abcs
At the programming language level, an ABC is a class that has one or more pure virtual member functions. You cannot make an object (instance) of an ABC.

But you wouldn't want to create a base-class object anyway.

An instance of a subclass ("daughter") of Vehicle needs to already exist so that its pointer can get push_back'd into your std::vector<Vehicle*>.

Careful! Once you start messing with pointers, you have to be very careful with knowing who is in charge of owning and deleting the dynamic memory.
Last edited on
+Peter
Oh... Its that simple :/ Thank you a lot, thats work perfectly :)

+Ganado
Yeah, I try to be careful with that. Here is how I delete the vector at the end of the program
1
2
3
4
5
6
7
8
void Garage::endProg()
{
    for (int i(0); i<m_garageList.size(); i++)
    {
        delete m_garageList[i];
        m_garageList[i] = 0;
    }
}


I hope this is enough

Topic archived. No new replies allowed.