Search code examples
c++functionclassboostmember

Same function with same signatures in the same class/struct? Overload?


I have seen a code portion in the boost example which is used to construct a state machine. What confused me is the two member functions ElapsedTime()? Is this allowed for the two functions to have the same signatures such as function name and parameters type?

I have googled a lot but without any luck to find relevant info about this. Any advice on this would be greatly appreciated.

struct Active : sc::simple_state< Active, StopWatch, Stopped >
{
public:
    typedef sc::transition< EvReset, Active > reactions;

    Active() : elapsedTime_( 0.0 ) {}
    double ElapsedTime() const { return elapsedTime_; }
    double & ElapsedTime() { return elapsedTime_; }

private: 
    double elapsedTime_;
};

Solution

  • Signature of a function is defined by the name and by the argument types. You have two functions with the same name, but they do not get the same arguments!

    You might wonder how could it be?

    So, each member function gets another parameter implicitly: this is the "this" pointer. A pointer to the object who called that method.

    When you add const in the end of the method, you specify the "this" argument as a const pointer to const. In the other method (without the const), the type of "this" is just const pointer.

    Hence, you have two methods with different signature, and there is no problem at all.