Skip to main content
gamedev.net
🔒 Locked

member Constructors after class Constructor?

Started by Yratelev Jan 25, 2004 at 12:10 PM 7 replies 350+ views
Original Post
Yratelev
Yratelev
Hi I want to know how to initialize a member constructor AFTER the base class has been constructed. eg; class A { A(); } class B { A B(); } A::A() { //need something from parent B here } B::B() :A() <- this initizializes before B is constructed { } :A() <- this is wot i want, but its illegal syntax Anyone know? cheers Stu
Yratelev
SiCrane
SiCrane
You can''t do that. C++ requires that all an object''s member objects be completely constructed before the constructor for the object is called. The best you can do is use an assignment operator or some other member function on the member object inside the parent object''s constructor.
IFooBar
IFooBar
you can give A an init function that takes a pointer to B


A::Init( B* b )
{
// Do stuff here instead of in constructor. Maybe make it a
// friend to access private B members directly...
}



then in B''s constructor
class B
{
A m_a;

B()
{
m_a->init( this );
}
};


| C++ Debug Kit :: GameDev Kit :: DirectX Tutorials :: 2D DX Engine | TripleBuffer Software |
| Plug-in Manager :: System Information Class :: D3D9 Hardware Enum | DevMaster :: FlipCode |

[size=2]aliak.net
temp_ie_cant_thinkof_name
temp_ie_cant_thinkof_name
Easy: empty the member's default constructor, then in the encapsulating class's consructor call the other constructor explicitly.

class C {
public:
C() {}
C(int i_) : i(i_) {}
protected:
int i;
};

class A {
public:
A(int i) /*: C() called here*/ {
DoSomeStuff(&i);
c.C(i);
}
protected:
C c;
};

Just make sure your default is empty, and/or don't call it at all, but I'm not sure.


[edited by - temp_ie_cant_thinkof_name on January 25, 2004 4:48:04 PM]
"I study differential and integral calculus in my spare time." -- Karl Marx
SiCrane
SiCrane
temp_ie_cant_thinkof_name: that class A constructor does not contain legal C++ code. The "c.C(i)" expression is pure garbage.
Sneftel
Sneftel
quote:
Original post by SiCrane
temp_ie_cant_thinkof_name: that class A constructor does not contain legal C++ code. The "c.C(i)" expression is pure garbage.

Indeed. Instead, try new (&c) C(i);. Of course, this is evil.


"Sneftel is correct, if rather vulgar." --Flarelocke
SiCrane
SiCrane
If you''re going to call placement new on it, at least call it''s destructor first.
VenDrake
VenDrake
You could use a pointer.



class A
{
public:
A(B b)
{/*do something with b*/}
};

class B
{
A * pA;
public:
B()
{ pA = new A(*this); }
};




-----------
VenDrake

"When you and a friend are being chased by a King Cheata, you have but one chance, trip your friend."
-------------VenDrakeTo understand recursion, you must first understand recursion.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.