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.
Related
I have a simple equation that needs to be called about 100 times throughout my code. I am trying keep function overhead to a minimum, but still use OOP concepts (which is new to me). The equation is just a simple one that calculates the max of two differences. It is like 3 lines. Should I use an inline function? If so, what is usually the accepted way to use it (i.e should I create a seperate .h file, put it in a base class(all the objects using this function are indirectly derived).
Unless your compiler has good Link Time Optimization features (and they are enabled), the entire function you want to inline must be declared and defined in a header file. As for dedicating a .h file solely for your inlined function, or where to put it in your class hierarchy, we couldn't tell you even if you gave us the rest of your code and/or design. It's really more a stylistic choice than predefined rules about the one and only correct way to do it.
EDIT: To clarify: if your inline function will only be used in a single source (.cpp) file, you can just declare it right in that same file as static inline. If you want it accessible to multiple source files, then put it in a header file.
Yes, you can use inline function members if they are not virtual. But in every file that uses this inline function should be present it's definition, so it's a good idea to put implementation of this function in *.h file. If it is virtual you can not use inline (although gcc allows it) according to the standard.
But in any case standard does not guarantee inlining your function - even if you mark it as inline.
I would not put such a function in a class unless it needs to use some of the state of the class, or if there is some good reason to limit its use to that class hierarchy.
An inline function inside a namespace in a .h sounds like it would be a good way to go. By putting it in a namespace you get to use the common name max without worrying about it being in the global namespace and you can then collect any functions fitting that domain there.
Though if it's just a max function maybe just using the std::max function would be a good option?
In general it's better to reuse if possible. It saves time and reduces maintenance costs. Everyone pretty much knows what std::max is but some other max takes some figuring out.
For now I do not use header files at all. Classes are each in a single .cpp file completely. But to save compile time I want to make use of header files now. My hope is that Visual Studio won't compile classes which weren't modified for debug builds then.
Is there a way to mention only public methods and members in the header file. In theory that would be enough information for the compiler. If another file, say main.cpp includes the class header there is no need for private methods and members, is it?
How can I use header files without retyping the names of private methods and members? The reasons for me to want so is coding productivity. When I want do add a small helper function to the class used by another method, I don't want to have to also add it's signature to the header file.
If another file, say main.cpp includes the class header there is no need for private methods and members, is it?
No, public methods and members aren't necessarily enough. For example, if another .cpp file were to try and create an instance of your class:
SomeClass instance;
the compiler will need to know, among other things, how much memory to allocate for SomeClass. For that it requires full knowledge of SomeClass's private data members.
The way you are framing the question makes it sound as if you were intent on fighting the language. I don't think that's a good way to go about it. I think the best way is to do things the way things are usually done in the language of your choice, and depart from that only when there is a specific, clearly understood need.
The way things are usually done in C++ is that the entire class declaration goes in the header file, and the definition is in some way split between the header file and the corresponding .cpp file. The exact split is determined by various technical considerations. For example, templates and inline functions normally have to appear in the header file. On the other hand, placing code in header files increases dependencies and potentially build times.
There are ways to address these issues. However, since this involves extra complexity, I'd argue that this should only be done if there is a clearly identifiable need.
I don't know of a way to do what you're asking, but there is another way to give some isolation. You might want to take a look at the pimpl idiom as it offers isolation about private information. It's a little bit of extra work, but it can be extremely useful, especially in large projects.
All function declarations should go in header files and all function definitions should go in cpp files. It's not good coding practice to put declarations inside the cpp files.
You could put definitions inside headers though, when you write templates or inline functions.
Once you declare the class in the header file, you have to declare all its methods and members inside the class' declaration in the header, given that your class is no longer declared in the cpp file.
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().
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...
Most C++ class method signatures are duplicated between the declaration normally in a header files and the definition in the source files in the code I have read. I find this repetition undesirable and code written this way suffers from poor locality of reference. For instance, the methods in source files often reference instance variables declared in the header file; you end up having to constantly switch between header files and source files when reading code.
Would anyone recommend a way to avoid doing so? Or, am I mainly going to confuse experienced C++ programmers by not doing things in the usual way?
See also Question 538255 C++ code in header files where someone is told that everything should go in the header.
There is an alternative, but the cure is worse than the illness — define all the function bodies in the header, or even inline in the class, like C#. The downsides are that this will bloat compile times significantly, and it'll annoy veteran C++ programmers. It can also get you into some annoying situations of circular dependency that, while solvable, are a nuisance to deal with.
Personally, I just set my IDE to have a vertical split, and put the header file on the right side and the source file on the left.
I assume you're talking about member function declarations in a header file and definitions in source files?
If you're used to the Java/Python/etc. model, it may well seem redundant. In fact, if you were so inclined, you could define all functions inline in the class definition (in the header file). But, you'd definitely be breaking with convention and paying the price of additional coupling and compilation time every time you changed anything minor in the implementation.
C++, Ada, and other languages originally designed for large scale systems kept definitions hidden for a reason--there's no good reason that the users of a class should have to be concerned with its implementation, nor any reason they should have to repeatedly pay to compile it. Less of an issue nowadays with faster systems, but still relevant for really large systems. Additionally, TDD, stubbing and other testing strategies are facilitated by the isolation and quicker compilation.
Don't break with convention. In the end, you will make a ball of worms that doesn't work very well. Plus, compilers will hate you. C/C++ are setup that way for a reason.
C++ language supports function overloading, which means that the entire function signature is basically a way to identify a specific function. For this reason, as long as you declare and define function separately, there's really no redundancy in having to list the parameters again. More precisely, having to list the parameter types is not redundant. Parameters names, on the other hand, play no role in this process and you are free to omit them in the declaration (i.e in the header file), although I belive this limits readability.
You "can" get around the problem. You define an abstract interface class that only contains the pure virtual functions that an outside application will call. Then in the CPP file you provide the actual class that derives from the interface and contains all the class variables. You implement as normal now. The only thing this requires is a way to instantiate the derived implementation class from the interface class. You could do that by providing a static "Create" function that has its implementation in the CPP file.
ie
InterfaceClass* InterfaceClass::Create()
{
return new ImplementationClass;
}
This way you effectively hide the implementation from any outside user. You can't, however, create the class on the stack only on the heap ... but it does solve your problem AND provides a better layer of abstraction. In the end though if you aren't prepared to do this you need to stick with what you are doing.