C ++: function in the class for several variable values

advertisements

a bit of a noob problem. Inside a class called 'cell', I have an enum 'Example' say

  typedef enum Example
  {
      E1=0,
      E2,
      E3,
      E4
  };
  Example inputValueE;

Also I have a function inside class as follows

  void evolveE(Example type_);

Outside the class, I attempt to define the function for several types as follows

void cell::evolveE(Example type_ = E1){****some stuff****;};
void cell::evolveE(Example type_ = E2){****some diff stuff****;}; ***etc***

I've played around with these a bit but with no luck. The problem is i'm not allowed to redefine the same function. I was going to use the switch-case type command which is always backup although i'm pretty sure there is a more elegant way to do this

Any help is much appreciated.


When overloading a function (providing more than one function with the same name in a class), you need to provide a different set of argument types to each function like this:

void cell::evolveE(Example type_){****some stuff****;}
void cell::evolveE(OtherExample size_){****some diff stuff****;}

Notice that here, one function takes an argument of type Example and the other takes an argument of type OtherExample. Although you provide different default values in the function you are trying to overload, both functions take the same argument type and so the compiler has no way of telling the difference between them.

You could use a switch although I would prefer an if/else because it is less prone to bugs.

If the Example enum is really determining the type of your class you could use polymorphism. It is a very elegant feature of OOP. Then you could have something like this:

class cell
{
    ...
    virtual void evolveE() = 0;
};

class E1cell : public cell
{
    ...
    void evolveE()
    {
        // some stuff
    }
};

class E2cell : public cell
{
    ...
    void evolveE()
    {
        // some diff stuff
    }
};