Why are functions usually declared in classes and not defined?:
class MyClass {
public:
MyFunction(); //Function is declared not defined
};
Instead of:
class MyClass {
public:
MyFunction() {
std::cout << "This is a function" << std::endl;
} //Function is defined instead of being declared. No need for cpp file
};
Is the reason because it looks nice or easier to read?
CodePudding user response:
Generally, classes are declared in header files. Writing the definition in the header would run afoul of the one-definition rule. If I have
// my_class.h
class MyClass {
public:
void myFunction() {}
};
Then, as soon as I've included this file in two different .cpp
files, I have two separate definitions of MyClass.myFunction
, which is an error. Thus, we declare our class methods in the header and then write the implementation in the .cpp
source file.
// my_class.h
class MyClass {
public:
void myFunction();
};
// my_class.cpp
void MyClass::myFunction() {}
The rules are more complicated if the function is inline
or a template function, in which case there's a compelling (and often required) reason to define the function in the header. Some people will define template functions in the class itself as you've suggested, but others prefer to write the template function definition at the bottom of the header, to be more consistent with the way we write non-template functions. It's more a matter of style in this case, so pick your preferred convention and stick to it.
Likewise, if the class is not mentioned in a header file (i.e. if the class is an implementation detail and only exists in one .cpp
file), then you're free to do it either way, and you'll find folks that prefer both conventions.
CodePudding user response:
in one word, seperate implemention and declearation is always good.
in a large project, implemention in header file will cause multiple definition problem.
seperate them is always good way, can avoid a lot of future problems.