1

I've tried numerous ways to go about this but none of them worked. What I'm trying to achieve is this.

I have a class like this.

class Auton {
  public:
    int slot;
    const char * name;
    void run();
};

What I want to do is make the run function do different things. For example -

// The code below doesn't work, unfortunately :(

Auton one;
void one::run() {
  // Do something here
}

Auton two;
void two::run() {
 // Do something different here
}

Is this possible?

Latte
  • 51
  • 6
  • 2
    This sounds like an [XY problem](http://xyproblem.info) to me. – Uwe Keim Jun 24 '19 at 04:33
  • @UweKeim Sorry if it sounds like that :( I'm new to stack overflow and I don't know how to ask questions properly :I – Latte Jun 24 '19 at 04:36
  • 1
    `one` and `two` are objects of class `Auton` your member function s/b defined `void Auton::run(){..}` if you want to do different things with the object, use a different method like `run2` You can also use state info. That is, do different things depending on some member variable that is used to alter execution based on its value. – doug Jun 24 '19 at 04:45

2 Answers2

5

It is possible with Lambda expressions.

Example:

class Auton {
public:
    int slot;
    const char * name;
    std::function<void()> run;
};

Auton one;
one.run = [] {
    // Do something here
};

Auton two;
two.run = [] {
    // Do something different here
};
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Ugnius Malūkas
  • 2,649
  • 7
  • 29
  • 42
  • woah! ok, it'a solution, but is this a good advice and a good way to handle this kind of problem? I can't think about a situation where i will be happy to see code like that... what you can do and what you should do, are really different things IMHO – Federico Jun 24 '19 at 07:25
  • In my experience, I used this solution when implementation was dependent on Factory method, which generates required functionality. In the most cases, of course it is better to use inheritance. But it always depends on needs and requirements. – Ugnius Malūkas Jun 24 '19 at 08:13
4

That is unfortunately not possible. What is possible is:

class Auton {
public:
    // ...
    virtual void run();
};

class AutonOne : public Auton {
public:
    // ...
    void run() override
    {
        // Do something
    }
};

class AutonTwo : public Auton {
public:
    // ...
    void run() override
    {
        // Do something different
    }
};

AutonOne one;
AutonTwo two;

Learn more about this here: Why do we need virtual functions in C++?

Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93