"Glenn Serpas" <no***@nowhere.net> wrote in message
news:C8*****************@newssvr23.news.prodigy.co m...
I have Class A and Class B .. Class B has a private member that is a
pointer to a Class A object.
private:
B *mypointer ;
I instantiate the A object
A* myobject new = A();
How do I tell it to instantiate it's member mypointer ? I've tried several
options I've read about in my C++ book and on the web. The solutions I
found were to add the following to the contructions declaration in the
class header. However, it will not compile.
public:
A() { mypointer = new B() ; }
I've also tried adding instantitating the object in the contructor
implementation. This will compile, but will crash during execution.
A::A()
{
B* mypointer = new B() ;
}
I can only instantiate the mypointer if it is not a pointer (ie B
myBobject ;) I simply add it to the constructor implementation for class
A.
A::A() : myBobject()
{
}
Hopefully someone reading this message will have an approach that will
work for me. Thanks.
There are a couple of issues. First, you are implying that whenever you have
an A, you will always have a B that A will point to using mypointer. If this
is true, there are two cases.
1. B may or may not yet exist, but when it does A can point to it. Also, A
can be changed to point to different B's during execution.
2. B always exists, and is created if it doesn't whenever an A is created.
This means the B is a part of A -- always. For this case, it might be best
to make B a member of A and have it created automatically whenever an A is
created. Otherwise, do as you were doing with the creation of a new B in the
constructor of A. I will note that this may have failed to compile because
the compiler didn't know what a B was at the point you used it in the
constructor of A. For it to know, B must have been declared before the code
of A that uses the B class. This can be done by putting the B class
definition ahead of A's code.
In any event, if the case is 1. (B can be created later) you will need a
function in A that can be called to set the mypointer member to the address
of a B that is passed as an actual parameter to the function.
It is also possible to turn this around the other way -- letting a new B
create an A and setting the mypointer member of that A to itself.
It all depends on how the two classes are to interoperate.
I hope this helps.
--
Gary