C++: Avoid .cpp files with only an empty (de)constructor
Asked Answered
E

4

1

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?

Elman answered 17/6, 2010 at 10:16 Comment(1)
I though I tried that, and I got compile errors. Now I don't get errors anymore. Thanks all.Elman
S
9

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;
};
Sacral answered 17/6, 2010 at 10:19 Comment(0)
D
5

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

Deafen answered 17/6, 2010 at 10:19 Comment(1)
Thank you for sharing this rule of thumb. It is still the same in C++17 and I've spend some time lately trying to figure out how to make it work.Fingerbreadth
R
1

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.

Rutharuthann answered 17/6, 2010 at 10:19 Comment(0)
A
1
#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_ */
Angkor answered 17/6, 2010 at 10:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.