Re: pass address of data member to base class ctor?
Ralf Fassel wrote:
Is it possible to pass the *address* of a non-pod data member to a
base-class-ctor?
class bar {
public:
bar(base *x) : x_(x) {}
// goal: avoid defining docall virtual and having to repeat
// it in all derived classes
docall() { x->method(); }
private:
base *x_;
};
class foo1 : public bar {
public:
// HERE
foo() : bar(&x_){ };
// alternative, assumes a protected set_base() in base class
// foo() : bar(){ set_base(&x_); };
private:
derived1 x_;
};
I know I could delay the assignment into the CTOR of foo1, but by
having a mandatory argument in the base-CTOR I cannot forget to assign
the data member...
R'
So, basically you are attemping to call a member of a derived class from a
base class.
Wouldn't it be simpler to make x_ a base pointer in bar (as you already
have) and having foo's constructor create it?
class base
{
public:
virtual method() = 0;
};
class derived: public base
{
virtual method() { };
};
class bar
{
public:
bar(): x_( 0 ) {}
~bar() { delete x_; }
// goal: avoid defining docall virtual and having to repeat
// it in all derived classes
void docall() { x_->method(); }
protected:
base *x_;
};
class foo : public bar
{
public:
// HERE
foo() { bar:x_ = new derived; }
};
int main()
{
}
I'm not saying this is a good way to do it, only that it is a possible way.
You may notice that I am having base delete the instance instead of derived,
even though derived created the instance. Some may not think this is a good
thing, that derived should do it, but my thinking is it will be easier for
someone creating a new derived not to forget the deletion.
--
Jim Langston
tazmaster@rocketmail.com
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]