0

I have a problem with code in my project. I have base class Car and two derived classes Bus and Lorry. I define pure virtual function void add() and the thing is that I want it to add either Load or Passenger depending on which class it is called in eg. when I call function void add() for Bus I want it to add an object of class Passenger. I know that it is impossible to use different parameters in derived classes and I really want to avoid using templates. How can I do this? If not everything is clear, ask me. Thank you in advance.

class Car
{
public:
    friend std::ofstream& operator<<(std::ofstream&, const Car&);
    friend std::ifstream& operator>>(std::ifstream&, Car&);
    void view();
    virtual void add() = 0;
    virtual void remove() = 0;
    virtual ~Car();
protected:
    Car() = delete;
    size_t _weight, _number_of_passengers;
    std::string _name;
    Engine _engine;
    Passenger* _passengers = nullptr;
    Load _load;
};

class Lorry : public Car
{
    Lorry() = default;
    size_t maximum_load;
public:
    void add() override;
    void remove() override;
    virtual ~Lorry();
};

  • I think this [link](https://stackoverflow.com/questions/55338931/polymorphism-with-different-parameters) may give you a good point of view. I hope it helps. – Mohammed Deifallah Jan 18 '20 at 13:12
  • Depending on design and usage of the classes, you could make `Car` a `template`, where the type of the argument for e.g. `add` is a template argument. – Some programmer dude Jan 18 '20 at 13:12
  • Does this answer your question? [Polymorphism with different parameters](https://stackoverflow.com/questions/55338931/polymorphism-with-different-parameters) – Mohammed Deifallah Jan 18 '20 at 13:13
  • [Double dispatch](https://eli.thegreenplace.net/2016/a-polyglots-guide-to-multiple-dispatch/)? – Evg Jan 18 '20 at 13:15
  • this sounds like you may acheive it using type erasure; But it will make you derived classes more complex. look for Passkey idiom tto, ,it may be helpfull – Blood-HaZaRd Jan 18 '20 at 13:22

0 Answers0