tags:

views:

607

answers:

5

I am fairly new to C++ and I have seen a bunch of code that has method definitions in the header files and they do not declare the header file as a class. Can someone explain to me why and when you would do something like this. Is this a bad practice?

Thanks in advance!

A: 

In C++, functions do not have to be members of classes.

anon
Not that my own answer was good, but I don't see how this answers "Can someone explain to me why and when you would do something like this. Is this a bad practice?". Obviously it's legal since he saw it in working code.
Uri
A: 

An H file is simply a way of including a bunch of declarations. Many things in C++ are useful declarations, including classes, types, constants, global functions, etc.

C++ has a strong object oriented facet. Most OO languages tackle the question of where to deal with operations that don't rely on object state and don't actually need the object.

In some languages, like Java, language restrictions force everything to be in a class, so everything becomes a static member function (e.g., classes with math utilities or algorithms).

In C++, to maintain compatibility with C, you are allowed to declare standalone C-style functions or use the Java style of static members. My personal view is that it is better, when possible, to use the OO style and organize operations around a central concept.

However, C++ does provide the namespaces facilities and often it is used in the same way that a class would be used in those situations - to group a bunch of standalone items where each item is prefixed by the "namespace" name. As others point out, many C++ standard library functions are located this way. My view is that this is much like using a class in Java. However, others would argue that Java uses classes because it doesn't have namespaces. As long as you use one or the other (rather than a floating standalone non-namespaced function) you're generally going to be ok.

Uri
As usual, your observations on C++ practice are wrong. C++ does not "prefer" classes.
anon
@Neil: C++ is typically taught for object oriented programming, especially now that C itself has been upgraded with a lot of things to make it more usable. I would still argue that OOP is preferable. But you really don't have to be such a prick about it.
Uri
Neil, I expect Uri meant that C++ *programmers* prefer classes, which is true in my experience (although subjective).
ChrisW
The C++ Standard Library would tend to contradict both of you - all the algorithms are non-member functions.
anon
@Uri I couldn't give a monkeys how C++ is taught - I'm interested in how it is used.
anon
@Neil: I would hope that C++ is typically used as it is taught. If you strip away OOP and references from C++, you've got a slightly shinier C. The hardest point of teaching is to get people to think in OOP term. Yes, the C++ standard library is often in C style, probably to make it more accessible. As I stated, both are an option, unlike Java. I personally don't think the C style is superior.
Uri
@Neil You're right if you're saying that classes aren't *always* prefered (c.f. the standard 'algorithms').
ChrisW
lol @Neil. You got the list of people's c++ preferences of SO? I'm eager to read it. Can you mail me?
Johannes Schaub - litb
i agree with neil. The Standard as of c++1x tends to prefer non-member functions. for example: thread_id() and yield() are not static members of thread class, but free functions within std::this_thread . Also, templates in C++1x will use free functions to interface with archetypes: template<Container C> void f(C } , NOT c.begin(), c.end() . Time has teached C++ lovers that free functions are superior :p
Johannes Schaub - litb
@litb please clarify "you got the list of people's c++ preferences of SO?" - I don't think I said that.
anon
i was kidding :) just find it amusing how you remember his observations about C++ practices hehe
Johannes Schaub - litb
Btw, nothing wrong with that. I have some people in mind that i (and others, too) told some errors in their answer (logical errors, not just typos). And they don't think about fixing them, apparently. What i do as a result: Not voting them up before they haven't fixed outstanding issues :p
Johannes Schaub - litb
The standard libraries IMHO are actually not the best example because they make consistent use of namespaces, and thus achieve a very similar effect to nonstatic member functions in other languages (e.g., Java). You don't just have "free-floating" nonmember functions.
Uri
@litb: I'm glad everyone is having a good laugh at my expense. I have no problems changing answers and retracting them - we all make mistakes or have unpopular opinions. That being said, I feel Neil's tone could have been more respectful, especially when his own answer "it's legal" had very little to do with what the OP had asked about
Uri
@Uri, i'm sorry i don't mean you with the peoples i have in mind. You are all fine i think, hehe
Johannes Schaub - litb
+5  A: 

Is this a bad practice?

Not in general. There are a lot of libraries that are header only, meaning they only ship header files. This can be seen as a lightweight alternative to compiled libraries.

More importantly, though, there is a case where you cannot use separate precompiled compilation units: templates must be specialized in the same compilation unit in which they get declared. This may sound arcane but it has a simple consequence:

Function (and class) templates cannot be defined inside cpp files and used elsewhere; instead, they have to be defined inside header files directly (with a few notable exceptions).

Additionally, classes in C++ are purely optional – while you can program object oriented in C++, a lot of good code doesn't. Classes supplement algorithms in C++, not the other way round.

Konrad Rudolph
+3  A: 

It's not bad practice. The great thing about C++ is that it lets you program in many styles. This gives the language great flexibility and utility, but possibly makes it trickier to learn than other languages that force you to write code in a particular style.

If you had a small program, you could write it in one function - possibly using a couple of goto's for code flow.

When you get bigger, splitting the code into functions helps organize things.

Bigger still, and classes are generally a good way of grouping related functions that work on a certain set of data.

Bigger still, namespaces help out.

Sometimes though, it's just easiest to write a function to do something. This is often the case where you write a function that only works on primitive types (like int). int doesn't have a class, so if you wanted to write a printInt() function, you might make it standalone. Also, if a function works on objects from multiple classes, but doesn't really belong to one class and not the other, that might make sense as a standalone function. This happens a lot when you write operators such as define less than so that it can compare objects of two different classes. Or, if a function can be written in terms of a classes public methods, and doesn't need to access data of the class directly, some people prefer to write that as a standalone function.

But, really, the choice is yours. Whatever is the most simple thing to do to solve your problem is best.

You might start a program off as just a few functions, and then later decide some are related and refactor them into a class. But, if the other standalone functions don't naturally fit into a class, you don't have to force them into one.

Scott Langham
A: 

I am fairly new to C++ and I have seen a bunch of code that has method definitions in the header files and they do not declare the header file as a class.

Lets clarify things.

method definitions in the header files

This means something like this: file "A.h":

class A {
void method(){/*blah blah*/} //definition of a method
};

Is this what you meant?

Later you are saying "declare the header file". There is no mechanism for DECLARING a file in C++. A file can be INCLUDED by witing #include "filename.h". If you do this, the contents of the header file will be copied and pasted to wherever you have the above line before anything gets compiled.

So you mean that all the definitions are in the class definition (not anywhere in A.h FILE, but specifically in the class A, which is limited by 'class A{' and '};' ). The implication of having method definition in the class definition is that the method will be 'inline' (this is C++ keyword), which means that the method body will be pasted whenever there is a call to it. This is:

  • good, because the function call mechanism no longer slows down the execution
  • bad if the function is longer than a short statement, because the size of executable code grows badly

Things are different for templates as someone above stated, but for them there is a way of defining methods such that they are not inline, but still in the header file (they must be in headers). This definitions have to be outside the class definition anyway.

poliklosio