Archived

This topic is now archived and is closed to further replies.

HellRiZZer

One call to constructor when inheriting class..

Recommended Posts

HellRiZZer    308
Hi guys, I''ve been wondering how to call only ONE constructor when you derive a class from the other one? For example, I got:
class CFoo
{
public:
int i;

CFoo() { int i=0;}
virtual ~CFoo() {};
};

class CBoo : public CFoo
{
public:
CBoo() {i = 1;} // Problem occurs here, it calls CFoo::CFoo, I don''t need that!

virtual ~CBoo() {}
};

Thanks. " Do we need us? "

Ionware Productions - Games and Game Tools Development

Share this post


Link to post
Share on other sites
HellRiZZer    308
No, I think you didn''t understood (or maybe I described it wrong)

I got a class and a member pointing to an interface:


class IBlah
{
public:
...
...
etc
};

class CFoo
{
public:
IBlah *m_pBlah;

CFoo()
{
m_pBlah = new IBlah;
etc
};

class IBleh : public IBlah
{
public:
int fark;
etc
};

class CBoo : public CFoo
{
public:
...
...
CBoo()
{
// Here comes the problem - I want m_pBlah to point to IBleh, not IBlah

m_pBlah = new IBleh;
}
};


So, what I need is that each class derived from IBlah (or other above it - e.g class CKoo : public CBoo ) will call ONLY its constructor, and won''t go thru others that it derived from.

Thanks.


" Do we need us? "


Ionware Productions - Games and Game Tools Development

Share this post


Link to post
Share on other sites
Chacha    138
Perhaps you could write a ''dummy'' constructor in your base class, that will be called by each derived class constructor:


class CFoo
{
public:
CFoo() { i = 0; };

protected:
int i;
CFoo(short i, long j) { /*Do nothing*/ };
};

class CBoo : public CFoo
{
public:
// This default CBoo constructor calls the dummy CFoo

// constructor that does *nothing*

CBoo(): CFoo(0, 0) { i = 1; };
};

Share this post


Link to post
Share on other sites
spock    217
The base class constructor must be called. Magmai showed you the way to do it properly - initialize the base class member through a constructor argument:


class CFoo
{
public:
IBlah *m_pBlah;

CFoo(IBlah* bptr) : m_pBlah(bptr) { }
};

class CBoo : public CFoo
{
public:
CBoo() : CFoo(new IBleh) { }
};

Share this post


Link to post
Share on other sites
dmikesell    157
Do you have some sample code from your program? Perhaps inheritance is the wrong solution for your problem anyway.

--
Dave Mikesell
d.mikesell@computer.org
http://davemikesell.com

Share this post


Link to post
Share on other sites