Jump to content
  • Advertisement
Sign in to follow this  
BrickInTheWall

Class definitions in C++

This topic is 3019 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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
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_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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!