Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ class implementation namespace

I have files MyClass.hpp and MyClass.cpp

MyClass.hpp

class MyClass {
public:
    void method1();
    void method2();
};

MyClass.cpp

#include "MyClass.hpp"
void MyClass::method1() {
}

void MyClass::method2() {
}

I find it a little silly that I have to write out the MyClass:: every time I have to write a method implementation. Is there some sort of syntactic sugar that lets me just group all my implementation together?

Perhaps something like

namespace MyClass {
    void method1() {
    }

    void method2() {
    }
}

I don't mind using C++11 features, but I would like to stick with portable solutions.

EDIT:

I realize that the code above as written wouldn't work. I was just using it as an illustration of how I imagine some syntactic sugar would work to make things more convenient.

like image 995
math4tots Avatar asked May 10 '26 23:05

math4tots


1 Answers

No, it is not possible.

The only way is to define your member functions directly inside the class definition, which makes them inline and may or may not be what you want.

Personally, I reckon having function definitions in source files is well worth having to type out a class name once in each.

like image 193
Lightness Races in Orbit Avatar answered May 12 '26 12:05

Lightness Races in Orbit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!