0

I have recently created a class inheriting from another preexisiting one

class Child: public Parent{
    ...
};

and another class that contains a reference to a vector of parents

// foo.h
class Foo{
private:
    std::vector<Parent>& things;
public:
    Foo(std::vector<Parent>& things);
    // + a bunch of other member functions
};

The members are implemented in a separate file

// foo.cpp
Foo::Foo(std::vector<parent>& things):things(things){}
// ... other member functions of Foo 

I want to make Foo work with vectors of typestd::vector<Child> as well.

I am aware I could make Foo a template

template<class c>
class Foo{
...

and add the following lines to the end of foo.cpp to avoid linker errors

template class Foo<Parent>;
template class Foo<Child>;

This is not ideal because in the future Child likely not going to remain the only class inheriting from Parent and touching Foo.cpp every time a child of Parent is born seems not like an elegant solution to me. Is there a better way, than making Foo a template?

cmmnn
  • 315
  • 3
  • 10
  • 3
    Use *pointers* to the base (`Parent`) class? Then you can add pointers to any child class as well. Works very well with polymorphism. – Some programmer dude Apr 08 '21 at 17:41
  • 2
    Implement the template [in the header](https://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file). – 1201ProgramAlarm Apr 08 '21 at 17:43
  • 2
    Does Foo's vector own the Parent things? Then for polymorphism, it should be `std::vector> things;` If it does **not** own the Parent objects in the things, then for polymorphism it should be `std::vector things;`. – Eljay Apr 08 '21 at 17:46
  • @Someprogrammerdude and Eljay are right, pointers would be a smart solution, but would mean I need to touch all the code accessing elements of things. I will probably go with 1201ProgramAlarm's suggestion of moving the implementation to the header, since there are significantly less occurrences of Foo that I'd need to change. – cmmnn Apr 08 '21 at 17:55
  • If you want to allow mixed vectors (parents and children or different children together), you need a vector of pointers. If you want to disallow them, you probably need a template (but then you might ask yourself if inheritance is really appropriate here). – n. m. could be an AI Apr 08 '21 at 18:13
  • Ehmm, ok, but polymorphism works also with references, you know? – MatG Apr 08 '21 at 20:10

0 Answers0