CocaCola
CocaCola

Reputation: 763

Issue creating a function within a class

I'm trying to set up a new class with a play() function. I'm not sure what I'm doing wrong, because I have other classes which I have implemented in similar ways, and they work fine. Can somebody point out where I may have made an error?

.h file

#ifndef GAME_H
#define GAME_H

#include <string>
using namespace std;

class Game {
public:
Game(); 
void play();
};
#endif

.cpp file

#include "game.h"

#include <string>
#include <iostream>

using namespace std;

Game::Game() {}

Game::play() {}

I call the play function as follows:

Game* theGame = new Game();
theGame->play();

I am getting the following errors when I compile:

game.cpp:10: error: ISO C++ forbids declaration of ‘play’ with no type
game.cpp:10: error: prototype for ‘int Game::play()’ does not match any in class ‘Game’
game.h:16: error: candidate is: void Game::play()
game.cpp:10: error: ‘int Game::play()’ cannot be overloaded
game.h:16: error: with ‘void Game::play()’

Upvotes: 0

Views: 74

Answers (3)

CyberGuy
CyberGuy

Reputation: 2813

Game::play() {}

you should add type: void as a return type.

Upvotes: 2

juanchopanza
juanchopanza

Reputation: 227418

You forgot the return type:

void Game::play() {}

Upvotes: 2

Luchian Grigore
Luchian Grigore

Reputation: 258618

First error:

Game::play() {}

should be

void Game::play() {}

Second one - you have using namespace std; in your header. Never do that. Not an error per-say, but bad practice.

Third - you have #include <string> in the header, although you don't use string, so it's useless and can impact compilation time.

Fourth - you use new :). Please google smart pointers. This is C++ and raw pointers usage should be at a minimum.

Upvotes: 5

Related Questions