|
-
June 28th, 2010, 02:32 AM
#1
simple constructor question
I'm writing a simple game application. A game object is composed of a Board and an AI player. When the AI player is constructed it needs a reference to a board object, so it can interact with it. How can I set up the game class so that its members get constructed properly--considering that one needs a reference to another?
Code:
class Game
{
private:
Board theBoard;
AI computerPlayer; // AI needs reference to theBoard (above)
};
class AI
{
AI(Board& board_in) : theBoard(board_in)
private:
Board& theBoard;
};
Last edited by mjl3434; June 28th, 2010 at 02:36 AM.
-
June 28th, 2010, 07:26 AM
#2
Re: simple constructor question
Objects are constructed in the order they are declared, so could you do:
Game() : computerPlayer(theBoard) {
}
Or alternatively, have an initialisation function that takes a Board ?
your humble savant
-
June 28th, 2010, 03:48 PM
#3
Re: simple constructor question
When I try this there is a scope problem. I ran a simple test:
Code:
#include <iostream>
using std::cout;
class ObjectA;
class ObjectB;
class ObjectB
{
public:
ObjectB(ObjectA& refIn) : associatedObjectA(refIn)
{
cout << "Object B constructor.\n";
}
private:
ObjectA& associatedObjectA;
};
class ObjectA
{
public:
ObjectA()
{
cout << "Object A constructor.\n";
}
};
class Container
{
public:
Container() : theObjectB(theObjectA)
private:
ObjectA theObjectA;
ObjectB theObjectB;
};
int main()
{
Container myContainer;
return 0;
}
And the error I get is:
t.cpp: In constructor 'Container::Container()':
Line 32: error: 'theObjectA' was not declared in this scope
compilation terminated due to -Wfatal-errors.
Is it just that what I am doing does not make sense or is not possible?
-
June 28th, 2010, 04:25 PM
#4
Re: simple constructor question
The body for container constructor is missing.
 Originally Posted by mjl3434
When I try this there is a scope problem. I ran a simple test:
Code:
#include <iostream>
using std::cout;
class ObjectA;
class ObjectB;
class ObjectB
{
public:
ObjectB(ObjectA& refIn) : associatedObjectA(refIn)
{
cout << "Object B constructor.\n";
}
private:
ObjectA& associatedObjectA;
};
class ObjectA
{
public:
ObjectA()
{
cout << "Object A constructor.\n";
}
};
class Container
{
public:
Container() : theObjectB(theObjectA)
private:
ObjectA theObjectA;
ObjectB theObjectB;
};
int main()
{
Container myContainer;
return 0;
}
And the error I get is:
t.cpp: In constructor 'Container::Container()':
Line 32: error: 'theObjectA' was not declared in this scope
compilation terminated due to -Wfatal-errors.
Is it just that what I am doing does not make sense or is not possible?
-
June 28th, 2010, 10:58 PM
#5
Re: simple constructor question
Yes that's right. I got it working now. Thanks.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|