gorgabal
gorgabal

Reputation: 145

do I need to specify class for every function implementation in c++

If I have a header file that states

class fanStatusManager{


public:

    //default constructor
    fanStatusManager();

    public fanstatus_t setFanStatus(fanstatus_t status);

private:
    //etc
}`

and a cpp file that implements them:

fanStatusManager::fanStatusManager(){
    //default constructor TODOi
}

fanstatus_t fanStatusManager::setFanStatus(fanstatus_t status){
     //TODO: imlement this!
     assert(false);
}

I get a bit tired of typing "fanStatusManager::" before every implementation. Is it possible to circumvent this somehow?

Upvotes: 1

Views: 228

Answers (2)

Peter
Peter

Reputation: 36597

You can inline the member functions within the class definition

class fanStatusManager
{

   public:

     //default constructor
      fanStatusManager()
      {
           //default constructor TODOi
      };

     fanstatus_t setFanStatus(fanstatus_t status)
     {
          //TODO: implement this!
          assert(false);
     };
  private:
     //etc
 };

The downside of this is that, whenever you change the implementation of a member function, you are changing the header file that defines the class. That forces recompilation of EVERY compilation unit (aka source file) which depends on the header file.

In practice, unless your project is extremely SMALL and TRIVIAL (e.g. everything lives in a single source file) you are better off NOT doing this, except for very specific cases (e.g. accessors that will never be changed). The effort of typing fanStatusManager will be incurred exactly once for each member function. That is much less significant than the time and boredom you will experience as you get to watch every source file be recompiled when you change the implementation of ANY member function ..... even compilation units that don't actually use the member function you have changed.

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726599

Although it is possible to avoid typing the name of the class if you place implementation in the header, i.e.

class fanStatusManager{
public:
    public fanstatus_t setFanStatus(fanstatus_t status) {
        //TODO: imlement this!
        assert(false);
    }
}

there is no way to work around this if you are implementing member-functions separately. This is because C++ allows free-standing functions, i.e. this syntax is perfectly valid:

fanstatus_t setFanStatus(fanstatus_t status) {
    //TODO: imlement this!
    assert(false);
}

The above defines a free-standing function called setFanStatus which is not associated with any class.

Upvotes: 1

Related Questions