Using a child class as a parameter of a function in it's parent class

Hello All!

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?

Thanks in advance :)
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.
Last edited on
> 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
#include <vector>
#include <type_traits>

struct parent
{
    virtual ~parent() = default ;

    virtual int mem_fun_parent( int a ) { return i += a ; }

    template < typename DERIVED >
    int mem_fun2_parent( std::vector<DERIVED> children )
    {
        static_assert( std::is_base_of<parent,DERIVED>::value, "class must be derived from parent" ) ;
        int s = 0 ;
        for( DERIVED& d : children ) s += d.mem_fun_parent( this->parent::mem_fun_parent(10) ) ;
        return s ;
    }

    private : int i = 5 ;
};

struct child : parent { /* ... */ };

int main()
{
    std::vector<child> children(100) ;
    parent p ;
    std::cout << p.mem_fun2_parent(children) << '\n' ;
}

http://coliru.stacked-crooked.com/a/42c781c38aad772b
Topic archived. No new replies allowed.