I aware of three different kind of implementation "locations" for my class methods:
1) Define the method inside my class (.h file) and implement it in my .cpp file
//.h
class Foo
{
int getVal() const;
};
//.cpp
int Foo::getVal() const
{ return 0; }
2) Define and implement the method inside my class (.h file).
//.h
class Foo
{
int getVal() const
{ return 0; }
};
3) Define the method inside my class and implement it outside the class but inside my header file.
//.h
class Foo
{
int getVal() const;
};
int Foo::getVal() const
{ return 0; }
What are the main differences between these three approaches?
There are three elements to this question: readability (how good the code looks), compilation (how much the compiler can optimize it) and implementation hiding (If you use the code as a library, you may not want to explicitly share your special sauce with the world).
Method one exposes only the interface for the function in the header file. This means you show a nice clean interface, and your implementation is not exposed in plaintext. However, the code cannot be inlined across compilation units, so it has the potential to be a little slower in runtime (in practice, this only matters for a very, very very small percentage of the code). THIS SHOULD BE YOUR DEFAULT WAY TO GO.
Method 2 is implicit inlining. Long functions will clutter up your class which (imho) is bad. Also exposes your implementation to the world. However, the function can be inlined and is less verbose than defining it in another place. I reserve this for very small functions.
Method 3 is actually illegal, as you will break the one-definition rule, but the following is fine:
//Foo.h
class Foo {
int getVal() const;
};
inline int Foo::getVal() const {
return 0;
}
I use this when I want to keep the class definition clean but want the function definition in the header file (for inlinable or template functions).
(1) will compile faster for a large project (only have to compile the definition of getVal once in Foo.cpp, and only have to recompile one thing if definition changes), and you get a very clear interface for a class for people who want to look it up. On the other hand, you can't inline getVal().
(2) and (3) will compile slower and add way more dependencies to your definitions changing. But you can inline getVal(). Also this is required if getVal is a template function. NOTE (3) will cause linker errors if your header is included multiple times - you'll have to mark remember to label your function inline. This is a good reason to prefer (1) and (2) to (3).
Really it's not a matter of picking (1) vs (2). You will probably use both in large projects - put the definitions of the functions that should be inlined (and templates) in the header, and put the ones that inlining makes less sense for in the cpp.
A minor note before I begin, there are lots of words that are very similar used to describe these things, I will be using declaration for the portion in the header file (int getVal() const) and implementation for the portion in the cpp file (int Foo::getVal() const). Apologies if these aren't perfectly accurate.
Also note that benefits are penalties for the others, in case that isn't clear.
1) Define the method inside my class (.h file) and implement it in my .cpp file
This is considered the standard method, and generally accepted to be the default (there are numerous exceptions, so default might be a little strong).
It separates the declaration from the implementation. This provides a few benefits:
You only need to compile the implementation once. This could potentially save compilation time.
You only need the declaration to reference. This can avoid ordering issues and is vital for circular references between classes.
You don't distribute your implementation, this can be good for closed source systems as you often have to distrbute lots of your .h files for others to plug into your system.
2) Define and implement the method inside my class (.h file).
This is called an inline implementation, it should be used in simple implementations only. It has a few benefits too:
Most compilers take this as a huge inline hint. It doesn't guarantee inling but it is very likely, which for simple methods can be a win. Property style methods are a common example.
Your implementation is trivial to find as it is straight in the declaration.
3) Define the method inside my class and implement it outside the class but inside my header file.
I haven't seen this before, but would assume it is used when the definition is non-trivial but you want the inline benefits of 2. IdeaHat mentions that the inline keyword is required in this case.
Related
I have two functions, which are private members of class "Data":
class Date
{
private:
bool leapYear(int y);
void fillDate(int d, Month m, int y);
};
So, where is the best to define this functions:
in class definition;
in header file outside the class;
or in ".cpp" file?
You have the choice here. Here are some ideas to make your mind:
Inlining for speed is no longer a concern, since compilers are now good at link time optimization. So performance should not be a decision factor here (compilation speed matters too, but this is another bag of worms).
Small inline member functions, defined inside the class, may be an easy way to "document" what the class does. Also, this tends to keep the implementation localized, which is comfortable when reading the code. Don't overdo it however.
Large functions should in principle go into their own file, or at least outside the class definition, since they clutter the class definition code for no good reason. Template code is no exception.
Pimpl have advantages/disadvantages too, but here I don't see any good reason to introduce such beasts in your simple case. They are used typically to reduce dependencies between header files.
Here, if the implementation is small, you can write the code inline, inside the class. But you should put them in their own implementation (".cpp") file, if the logic is complex.
You can also start inline, and when the code has settled to something more complex, move the implementation to its own file.
I strongly discourage you to consider option 2. This gets you "Multiple definition" error by the linker if you include this file in more than one implementation file, because the definition will be copied (by the preprocessor) to each .cpp file.
My personal philosophy about this is to put all function definitions into the implementation (.cpp) file, because, first of all, it separates declarations (+ documentation) from definitions which adds to code clarity IMO, and, secondly, having all definitions in one place (the implementation file) makes it easier for me to find functions. In my experience it was always quite a nuisance to have to switch between header and implementation files to see whether this particular function I'm looking for was inlined / defined in the header or if it was in the implementation file. Having all function definitions in the implementation file means I know I will find the definition of any function in that file, and won't have to waste time switching and looking around.
I am working with a book on c++ and to solve the problems I am always asked to declare the member functions' prototypes in the xxxxxx.h file and define the functions body properly in the xxxxxx.cpp file. Is there any harm or disadvantage in defining the member functions in the .h file? If not, is there any benefit or advantage in defining them in the .cpp file?
If you will always write your code in .h files you will never be able to performa some technics, such as forward declaration. Since you can't use forward declaration if writing code in headers you will be not able to solve cross dependencies.
So you will need to include everything you need in .h file. Including this file in other file will include everything already included. Thus any small change in you code will result in almost full recompilation in many cases.
Also it's harder to read the code in .h files because you expect to see the interface of the class in .h, not implementation.
If you define the method in the header, you have to mark it as inline or define them inside the class definition to prevent multiple definitions:
//A.h
class A
{
void f()
{
}
void g();
};
inline void A::g()
{
};
Other than that, it's a matter of coding style. You generally keep your headers clean, as to only provide an interface to work with the class, and abstract away the implementation details.
Generally. There are cases where you have to define the functions in the header (templates) or when you want to (to allow better compiler optimizations).
This is the declaration in the header file:
class PrimeSieve
{
populate(int lim);
vector<int> sieve;
long long limit;
public:
unsigned int limit();
};
Should I define the accessor method in the .cpp file or in the .h, inline?
I'm new to C++, but I'd like to follow best practices. I've seen this around in some of the books—is this considered standard?
unsigned int limit() { return limit; };
Definitely write the accessor inline in the header file. It makes better optimizations possible, and doesn't reduce encapsulation (since changes to the format of private data require recompiling all units that include the header anyway).
In the case of a complicated algorithm, you might want to hide the definition in an implementation file. Or when the implementation requires some types/header files not otherwise required by the class definition. Neither of those cases applies to simple accessors.
For one-liners, put it inside the class definition. Slightly longer member functions should still be in the header file, but might be declared explicitly inline, following the class definition.
Most newer compilers are smart enough to inline what is necessary and leave everything else alone. So let the compiler do what its good at and don't try to second guess it.
Put all your code in the .cpp and the code declarations in the .h.
A good rule of thumb is to put all your code in the .cpp file, so this would argue against an inline function in the .h file.
For simple data types in classes fully visible to clients of the class, there is no real difference as you need to recompile the client whenever the class definition changes.
The main reason to make an accessor rather than use the member directly is to allow the implementation to remove the data member later on and still keep the interface compatible; if the interface containing the accessor is unchanged, the result is typically binary compatible, otherwise, it's source compatible. Having the accessor inline means defining it as part of the interface that you are changing, so you can ever only be source compatible.
The other reason to have an accessor is a DLL boundary: If your accessor needs to call into another function, and you allow it to be inlined, then this function's symbol needs to be exported to the client as well.
Depending on the complexity of the project, it can be beneficial to define an interface for your code as an abstract class, which allows you to change the implementation to your heart's content without the client ever seeing the change; in this case, accessors are defined as abstract in the interface class and clients cannot inline them, ever.
The argument for declaring the accessor inline is that this eliminates the call over-head, and can enable some further optimisations.
My experienced of measured performance is that the gain from doing this is usually rather modest. I consequently no longer do it by default.
More than being kind of global programming standards, these vary from organizations to organizaions. Of course, getLimit() would still be better than mere limit().
I am learning C++ and not quite sure about the Scope Resolution Operator.
suppose I have the following code:
code 1:
class Student {
int no;
int semester;
char grade[M+1];
public:
void display() const;
};
void Student::display() const {
cout << "Hi!" << endl;
}
code 2:
class Student {
int no;
int semester;
char grade[M+1];
public:
void display() const{
cout << "Hi!" << endl;
}
};
any differences if I define the display() inside its class? if there is no difference, then why should I use the scope resolution operator?
There is one difference - if defined in the class the function behaves as if it were declared as inline. But this is no big deal, and the compiler may well ignore it. The big difference is that for large, multi-file projects, if you make a change to the function body defined in the header, EVERY other file that uses your header will have to be recompiled. Whereas, if you make a change to the function body defined in a .cpp file, then only that file needs to be recompiled. This can and does make a huge difference to real-world projects.
The scope resolution operator allows you to define the function outside the class.
This provides the ability to not expose/abstract your source code implementation from the users of your library. The class declarations are placed in header files and the actual definitions are kept in a cpp file and then only the object files or libraries of the same are provided to the end user.
You can say it provides oneway of protecting intellectual rights though the feature was not designed specifically for it.
Normally you would define the class in the header file and then implement it in the .cpp file. For the compiler to know what function belongs to which class, you use the Scope Resolution Operator, ie ::.
When you place the function directly inside your header like you showed in example two, you need to prefix it with the inline keyword, which tells the compiler to put that entire function inside the code where you are calling it. Normally you do this with very small functions and for speed considerations, using it a lot can lead to code bloat in your exe.
The main reason is that you don't want to clutter up the class
definition with all sorts of irrelevant implementation details,
like the implementation of a function. When the class is small,
with only one or two functions, and the functions are small,
with only one or two lines, it's not necessarily a problem, but
in real life, putting the function definitions in the class
itself very quickly leads to unreadable code; you want to keep
the external definition separate from the internal
implementation as much as possible. (On large projects, they'll
typically be maintained by different people anyway.)
What is the right approach to take:
Define the member (class) function inside the class?
Define the member (class) function outside the class?
Thanks.
Assuming you're talking about these three possibilities:
Method defined in class definition in header file.
Method define outside class definition in header file.
Method define outside class definition in implementation file.
Then project and company guidelines may force you to use (1) or (3) always.
When you have a choice, it's IMHO best to adapt to circumstances at hand, considering things such as
Do you want a header-only module? Then (1) as default, (2) possible.
Is the method a large beast? Then (2) or (3).
Template method specialization? Then (2) or (3).
There is a build-time problem (slow builds)? Indicates (3).
Template class? (1) or possibly (2)
But except where the choice is effectively forced on you, above all consider the clarity of your code.
Cheers & hth.,
A common advice is to keep headers as simple and clean as possible. Headers will be included by external code, and they will have to process everything that you have written there. If you write a method in the header, all translation units will compile that function, only so that the linker can discard all but one of them later on.
If your code has an internal dependency on a type or library that is not part of your interface, then by inlining the code of the member function in the class declaration the definition of that class or the headers of that library will have to be included in your header, and that means that you are leaking your implementation details to your users.
Unless the member function definition is trivial (in an informal sense) and doesn't introduce any additional dependencies I would normally define a member function outside of the class body in a separate source file.
It's often a matter of style but there are some cases in which it is necessary and many other cases in which it is desirable to define function outside of the class body.
For example, in the cases where you have interdependent classes and only a forward declaration of another class can be made available before the class definition, a member function which uses the definition of that other class can only be defined outside of the class body after a full definition of the other class has been provided.
Do you mean "in the class declaration / .h file" vs "in a .cpp file using ::" ?
If so I always go for the latter. When it comes to debugging, it's a lot easier to step through and see what's going on. It also helps declutter the class declaration, which doesn't need to know any implementation details"
If you want to define a function within a class the most basic syntax looks generally like:
class Object
{
int property;
void doSomething()
{
property=100;
}
};
If you want to define a function outside it is similar to declaring functions before main and in library files. In your class you have:
class Object
{
int property;
void doSomething();
};
Then somewhere after your class, after the main() function or in an included file you can have the definition:
void Object::doSomething()
{
property=100;
}
Some place classes in a header file and the definitions in a cpp file used by that header. Various techniques possible.
Both of these approaches are valid. Often I will include very small and/or core class functionality directly within the class and other functions which do heavier bulk work I tend to separate. Try to think the difference in coming upon your code and wanting to alter it.
if we see according to performance issue than it is more effective way to declare the function in the class . becouse at the compile time it conects all the funcation calls and other components so it will easy and must be faster to get all in one source...