views:

82

answers:

4

Hi,

When I have a header file like this:

#ifndef GAMEVIEW_H_
#define GAMEVIEW_H_

#include <SDL/SDL.h>

class GameView
{
public:
 GameView();
 virtual ~GameView();

 virtual void Update() = 0;
 virtual void Render(SDL_Surface* buffer) = 0;
};

#endif /* GAMEVIEW_H_ */

I need to create a .cpp file like this:

#include "GameView.h"

GameView::~GameView()
{

}

GameView::GameView()
{
}

This is a bit stupid. Just a .cpp file for an empty constructor and deconstructor. I want to implement that method simply in the header file. That is much cleaner.

How to do this?

+7  A: 

You can define your constructor and destructor (this is the proper term, use this instead of deconstructor) inline:

class GameView
{
public:
 GameView() {}
 virtual ~GameView() {}

 virtual void Update() = 0;
 virtual void Render(SDL_Surface* buffer) = 0;
};
Péter Török
+1  A: 
#ifndef GAMEVIEW_H_
#define GAMEVIEW_H_

#include <SDL/SDL.h>

class GameView
{
public:
 GameView() {}
 virtual ~GameView() {}

 virtual void Update() = 0;
 virtual void Render(SDL_Surface* buffer) = 0;
};

#endif /* GAMEVIEW_H_ */
reko_t
+1  A: 

I don't see your problem:

class GameView
{
public:
 GameView() {}
 virtual ~GameView() {}

 virtual void Update() = 0;
 virtual void Render(SDL_Surface* buffer) = 0;
};

And of course if the constructor does nothing, there is no need to provide it all.

anon
+4  A: 

I want to implement that method simply in the header file. That is much cleaner.

So be it.

// ...
GameView() { }
virtual ~GameView() { }
// ...

You don't even need to write this. The compiler provides a default constructor itself. The only thing you need is the destructor because it's not virtual by default.

In case you heard you need to define these in the .cpp file - this is sometimes needed if you have smart pointers in your class as members. A rule of thumb is that when you have smart pointers to in your class, and they point to a class that's just forward declared in the header, always provide constructors and destructors in the .cpp file where you actually define the pointed-to class. Otherwise you can get problems with deletion of incomplete classes (causing undefined behavior in many cases).

Johannes Schaub - litb
+1 for the pitfall
neuro