0

Let's say I have a base class called "Component"

class Component
{

public:
    virtual void init() = 0;

};

This base class requires derived classes to define an "init" function. However, this init function declaration enforces that the function accepts no input arguments. This is not what I want.

I'm looking for a method to enforce an "init" function but allow the derived class to vary in the number of arguments it accepts.

Depending on the component type, the derived class should accept varying number of inputs.

How would this be achieved in C++?

Examples

class DerivedComponent1 : Component
{
    void init(int arg1);
};

class DerivedComponent2 : Component
{
    void init(int arg1, int arg2);
};
4
  • 3
    Those are three different functions. In any case, if you have a pointer/reference to a Component, how would the caller of init know how many parameters to pass? Commented Aug 26, 2019 at 0:22
  • 2
    Sorry, this cannot be done in C++. C++ does not work this way. A subclass can only override a virtual method that has the same exact signature. This is fundamental. Commented Aug 26, 2019 at 0:51
  • You want to use a variadic function. It should work for a pure virtual. Commented Aug 26, 2019 at 3:37
  • How do you want to call those init functions? That might give us a clue how to achieve this. Commented Sep 16, 2019 at 16:55

1 Answer 1

1

You should consider using the switch statement instead of the virtual qualifier to solve this problem. Just choose one function definition and choose a default value or zero to bypass consideration of the parameter. It is too easy to get confused when you try to code this way about the thing the class had done, so your function must be fully commented and unit tested.

[EDIT for Clarification: You can consider the virtual qualifier in each new derived instance, but this isn't the solution to the problem you asked about. A Constructor or Destructor method has to have a very specific effect; otherwise, it is impractical to quality test the effect of a class, so when you need to rely upon a one-size-fits-all constructor, you can really only achieve that effect if you are pretty careful in the coding process]

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.