0

In C++, how can I achieve the following:

// player.h
#ifndef PLAYER_H
#define PLAYER_H
class Player {
    public:
        Player(Cake* cake);
}
#endif

// player.cpp
#include "cake.h"
#include "player.h"
Player::Player(Cake* cake) { }

// cake.h
#ifndef CAKE_H
#define CAKE_H
class Cake {
    public:
        Cake( );
}
#endif

// cake.cpp
#include "cake.h"
Cake::Cake() { }

// main.cpp
#include "player.h"
#include "cake.h"
int main() {
    Cake* cake();
    Player* player(cake); // This does not work

    return 0;
}

In other words, Have a Player pointer that takes a Cake pointer in it's constructor.

However, when I try compiling the application with g++ i get the following error: error: cannot convert ‘Cake* (*)()’ to ‘Player*’ in initialization.

It probably makes sense, but I'd like to know why I can't have a pointer that takes a pointer (in the constructor).

iammilind
  • 68,093
  • 33
  • 169
  • 336
whirlwin
  • 16,044
  • 17
  • 67
  • 98
  • What's wrong with automatic variables? `Cake cake; Player player(cake);` is much easier and better. – sbi Oct 28 '11 at 13:54
  • This is just a dummy application I made, the "real" application looks a bit different. I had some problems with inheritance when I did not use pointers (e.g virtual functions in the parent class seemed to get called every time when the purpose was to call a child class' inherited function. – whirlwin Oct 28 '11 at 22:57
  • 1
    Oh my. That sounds bad. You might want to get yourself [a good C++ book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – sbi Oct 29 '11 at 10:06

4 Answers4

2

This looks like a mistaken local initialization.

Cake* cake();
Player* player(cake);

needs to be rewritten to

Cake* cake = new Cake();
Player* player = new Player(cake);
Linus Kleen
  • 33,871
  • 11
  • 91
  • 99
2
Cake* cake();

Here cake is not a variable as you might assume. Compiler looks as if cake() is a forward declaration which returns Cake* and takes no argument.

It can be,

Cake cake;
Player *player = new Player(&cake);
iammilind
  • 68,093
  • 33
  • 169
  • 336
1

This is the proper C++ syntax:

Cake* cake = new Cake();
Player* player = new Player(cake); 
Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
1

Cake is an unknown type in player.h . Use a forward declaration:

// player.h

class Cake;

class Player
{
  private:
    Cake* m_cake;
  public:
    Player( Cake* c ) : m_cake(c) {}
};
codencandy
  • 1,701
  • 1
  • 10
  • 20