Derived class to take arg that is also derived

Hi

i have a base class with a pure virtual function called "add" that takes in a ref to a "base_struct"

i want any child class of "base" to have the function "add" and take in a child of "base_struct"

for example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
struct base_struct
{

};

struct child_of_base_struct : public base_struct
{

};

class base
{
   public:
      virtual void add(base_struct& base) = 0;

};

class child : public base
{
   public:
      void add(child_of_base_struct& child_base) override;

};


But when i run this, i get an error saying that the method "add" in "child" isn't overriding anything. So im guessing its simply not possible?

or is there another way to achieve this?
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
struct base_struct
{

};

struct child_of_base_struct : public base_struct
{

};

class base
{
   public:
      virtual void add(child_of_base_struct& child_base) = 0;

};

class child : public base
{
   public:
      void add(child_of_base_struct& child_base) override;

};

Last edited on
Thanks for the reply
But there are multiple classes that derive from base and they all have to take different structs :\

i just want to require every child class of "base class" to have a function "add" that takes in a struct that is a child of the "base_struct". (To ensure that they all have some "required" functionality")

For instance: "help" class's "add" function take in a help_struct, and "report" class's "add" function take in a "report_struct". And all the structs derive from "base_struct".

I'm not sure if this is possible without casting though
(which i would like to avoid because i dont want the function signatures to say that they take in a "base_struct" when really they are meant to take in a "help_struct")
Last edited on
From the parent class' perspective, why does the child need to have an "add" function? The parent only cares about a base& from its derived classes. Why not have an hierarchy like this? (Notice the protected function forces derived classes to provide their own public interface functions.)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
struct base_struct {};

struct child_of_base_struct : public base_struct {};

class base
{
   protected:
      void add(base_struct& base);
};

class child : public base
{
   public:
      void add(child_of_base_struct& child_base) { base::add(child_base); }
};


Since every "child" class disallows most of the other derived structs, you can't have a virtual function that all derived classes use directly.
Topic archived. No new replies allowed.