Question

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?

Was it helpful?

Solution

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;
};

OTHER TIPS

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).

#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 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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top