One call to constructor when inheriting class..

Started by
5 comments, last by HellRiZZer 20 years, 6 months ago
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

Advertisement
struct CFoo   {   CFoo(int x=0) : i(x)      {}   int i;   }; struct BFoo : CFoo   {   BFoo() : CFoo(1)      {}   };
- The trade-off between price and quality does not exist in Japan. Rather, the idea that high quality brings on cost reduction is widely accepted.-- Tajima & Matsubara
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 IBlahm_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

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

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) { }};

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
Thanks all, spoke has a correct solution I think.
Thanks again.

" Do we need us? "


Ionware Productions - Games and Game Tools Development

This topic is closed to new replies.

Advertisement