c++classmethods

How to separate class to .h and .cpp without need to rewrite entire path


When I define a class in header file, I must write entire it's path for every method. I'd want to still define it as a class. For example:

a.h:

class a {
  void main();
}

a.cpp:

#include "a.h"
class a { // still encapsulate to write without prefix
  void main() {
    // define it
  }
}

This code would give an error but can something similar actually be done?

What I mean is to define code for every method I must write a::main() {} which is not very readable for me. I asked whether it is possible to still define it in a way as in header.


Solution

  • What i mean is to define code for every method i must write "a::main() {}" which is not very readable for me.

    If you want to implement class methods separatly from the class definition itself (which is the one you have in the h file), the syntax of C++ requires you to use the a:: prefix.

    This is true whether you place the method definition in a cpp files, or even in the h file itself.

    The only way the syntax allows to implement a method without the prefix with the class name and ::, is if it is implemented inline inside the class definition, but it seems like it will not suit you because then in your case it will not be in cpp file.

    There is no other way around it.

    Readbility is a subjective matter, but I must say that I (as well as many other experiences C++ programmers) find it very readable.

    A side note:
    In this specific case you might want to use a namespace instead of a class, to group the functions. See the other answer by @anatolyg for more details.