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

3
  • What's wrong with automatic variables? Cake cake; Player player(cake); is much easier and better. Commented Oct 28, 2011 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. Commented Oct 28, 2011 at 22:57
  • 1
    Oh my. That sounds bad. You might want to get yourself a good C++ book. Commented Oct 29, 2011 at 10:06

4 Answers 4

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);
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

1

This is the proper C++ syntax:

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.