Archived

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

One call to constructor when inheriting class..

This topic is 5174 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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