I am currently having an issue with a piece of code that I am writing in which I need to use a vector of a child class as a parameter in a function in the parent class. Below is an example of my code:
1 2 3 4 5 6 7 8 9 10
#include "child.h"
#include <vector>
class parent
{
parent();
function(std::vector<child> children);
// rest of class here
}
When I do this my program doesn't compile. However if I try to forward declare, as shown in the following example, it once again refuses to compile:
1 2 3 4 5 6 7 8 9
#include <vector>
class child;
class parent{
parent();
function(std::vector<child> children);
// rest of class here
}
This time, it refuses to compile because it needs to know the full size of the class child in order to create the vector. I have no idea how to get around this, and being able to access the child is essential for my program, so what should I do?
When you talk about "parent" and "child", are you talking about inheritance?
If so, then what you're trying to do makes no sense. If your base class is dependent on a specific derived class, then your derived class is no longer a specialisation of the base - because the base is every bit as specialised as the derived class. In which case, there's no point deriving one from the other - you might as well combine them into one class.
If the data that you need from the child class is present in the parent class then just change the vector's data type into pointers to the parent and use the polymorphism feature.
EDIT: I did not previously see MikeyBoy's post. He brings up a point worth considering.
> This time, it refuses to compile because it needs to know the full size of the class child in order to create the vector.
Make it a function template, and the function won't be instantiated till the size of the derived class object is known; till the actual call to the function is seen.