Class definitions in C++

Started by
2 comments, last by Windryder 14 years, 2 months ago
Hi guys, I have a question concerning class definitions and where to put them in C++. I program in C#, but I'm getting back into C++. My question: Do I put the class and it's member declarations in a .h file and put the definitions of member functions for example, in a .cpp file, or everything in one? What I'm thinking: something.h:

class MyClass
{
public:
  MyClass();
};
something.cpp:

#include "something.h"
.
.
MyClass::MyClass()
{
.
.
}
Cheers, Chris
Fate fell short this time your smile fades in the summer.
Advertisement
You need the method declarations defined in a .cpp file (unless they are declared inline) or you can very easily get multiple definition errors at link time. The "common" practice is the same as in Java: each class declaration in its own <ClassName>.h file and that classes implementation in its own <ClassName>.cpp file. That practice isn't enforced in the compiler/linker as it is in java, but it's a convenient pattern.

It's also good practice to wrap all headers with #define include guards so you don't get compiler "symbol already defined" errors:

#ifndef SOME_UNIQUE_STRING#define SOME_UNIQUE_STRINGclass MyClass{    //implementation};#endif


-me
Moved to the For Beginners forum.
A good practice is to put the implementations of short, simple member functions in the header filed (declared inline) so that the compiler is given the opportunity to inline them. Larger functions are probably best left in the .cpp file as they are unlikely to be inlined anyway.

// Foo.hppclass Foo{public:    void complexFunction(); // Implementation in Foo.cpp    int getBar() const; // Implemented further down, allowing for inliningprivate:    int m_bar;};inline int Foo::getBar() const{    return m_bar;}


Notice how getBar() isn't implemented within the class declaration. This serves the purpose of separating what the class does from how it does it.

This topic is closed to new replies.

Advertisement