Sign in to follow this  
BrickInTheWall

Class definitions in C++

Recommended Posts

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

Share this post


Link to post
Share on other sites
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_STRING

class MyClass
{
//implementation
};

#endif



-me

Share this post


Link to post
Share on other sites
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.hpp

class Foo
{
public:
void complexFunction(); // Implementation in Foo.cpp
int getBar() const; // Implemented further down, allowing for inlining

private:
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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this