base class initialization via virtual methods

D

Dennis Jones

Hello,

I have a couple of classes that look something like this:

class RecordBase
{
};

class RecordDerived : public RecordBase
{
};

class Base
{
protected:
RecordBase *FRecord;
virtual RecordBase *CreateRecord() const = 0; // pure virtual
Base();
};

class Derived : public Base
{
protected:
virtual RecordBase *CreateRecord() const { return new RecordDerived; }
public:
Derived();
};

Base::Base()
: FRecord( CreateRecord() )
{
}

Derived::Derived()
: Base()
{
}

Derived d;

My trouble here is that I would like to initialize FRecord with an instance
of the appropriate type, based on the result of a call to the virtual
method, CreateRecord. However, this does not seem to be possible from the
initializer list. If I attempt to execute this code as-is, when the Derived
object, 'd', is created, the Base class constructor stumbles into the
pure-virtual CreateRecord() method because the derived class hasn't been
constructed yet, and therefore no Derived::CreateRecord exists yet.
Obviously, I could re-write my constructors like this:

Base::Base()
{
}

Derived::Derived()
: Base()
{

FRecord = CreateRecord();
}

However, I was hoping I could handle all initialization in the initializer
list so that I don't have to explicitly create the "FRecord" instance in the
constructor of every class that derives from Base. Is this at all possible,
or am I stuck with having to manually initialize FRecord on a per-derived
class basis?

Thanks,

Dennis
 
V

Victor Bazarov

Dennis said:
I have a couple of classes that look something like this:

class RecordBase
{
};

class RecordDerived : public RecordBase
{
};

class Base
{
protected:
RecordBase *FRecord;
virtual RecordBase *CreateRecord() const = 0; // pure virtual
Base();
};

class Derived : public Base
{
protected:
virtual RecordBase *CreateRecord() const { return new
RecordDerived; } public:
Derived();
};

Base::Base()
: FRecord( CreateRecord() )
{
}

Derived::Derived()
: Base()
{
}

Derived d;

My trouble here is that I would like to initialize FRecord with an
instance of the appropriate type, based on the result of a call to
the virtual method, CreateRecord. However, this does not seem to be
possible from the initializer list. If I attempt to execute this
code as-is, when the Derived object, 'd', is created, the Base class
constructor stumbles into the pure-virtual CreateRecord() method
because the derived class hasn't been constructed yet, and therefore
no Derived::CreateRecord exists yet. Obviously, I could re-write my
constructors like this:
Base::Base()
{
}

Derived::Derived()
: Base()
{

FRecord = CreateRecord();
}

However, I was hoping I could handle all initialization in the
initializer list so that I don't have to explicitly create the
"FRecord" instance in the constructor of every class that derives
from Base. Is this at all possible, or am I stuck with having to
manually initialize FRecord on a per-derived class basis?

It is possible if you allow for the "lazy construction" of the
'FRecord' member. Essentially, you need to forward all requests to
that member through a single bottleneck where you'll check whether
the object exists, and if not, create it using the call to the
virtual member. Something like

class Base {
Record *FRecord; // private!
protected:
Record *getRecord() { // protected for descendants to use
if (!FRecord)
FRecord = CreateRecord(); // calls virtual function
return FRecord;
}
};

Make sure 'Base' itself does not use 'FRecord' directly.

V
 
D

Dennis Jones

It is possible if you allow for the "lazy construction" of the
'FRecord' member. Essentially, you need to forward all requests to
that member through a single bottleneck where you'll check whether
the object exists, and if not, create it using the call to the
virtual member. Something like

class Base {
Record *FRecord; // private!
protected:
Record *getRecord() { // protected for descendants to use
if (!FRecord)
FRecord = CreateRecord(); // calls virtual function
return FRecord;
}
};

Oh, of course. I actually do this in another class, albeit for a different
reason -- I don't know why I didn't think of it here.

Thank you, Victor.

Dennis
 
R

Ron Natalie

Dennis said:
My trouble here is that I would like to initialize FRecord with an instance
of the appropriate type, based on the result of a call to the virtual
method, CreateRecord. However, this does not seem to be possible from the
initializer list. If I attempt to execute this code as-is, when the Derived
object, 'd', is created, the Base class constructor stumbles into the
pure-virtual CreateRecord() method because the derived class hasn't been
constructed yet, and therefore no Derived::CreateRecord exists yet.
Obviously, I could re-write my constructors like this:
If it was just virtual, it would just invoke the base class constructor.
Since it is pure virtual, you are invoking undefined behavior.
 
D

Dennis Jones

Ron Natalie said:
If it was just virtual, it would just invoke the base class constructor.
Since it is pure virtual, you are invoking undefined behavior.

I know, Ron...that's why I asked the question.

- Dennis
 
G

Grizlyk

Dennis said:
My trouble here is that I would like to initialize FRecord with an instance
of the appropriate type, based on the result of a call to the virtual
method, CreateRecord.

1.
Agree, ctor of any class is always virtual, I want to say, when you are
creating concrete class, you always call ctor of real class of object
which you are creating. So ctor can not be done more virtual.

2.
The goal of ctor just does initialize of resources _declared in the
class_, no more. When you are calling virtual method of derived, you
need context (data) of derived (declared in derived class), but the
derived context still not exist.

If you are think, that context of derived already must exist, describe
the correct construction sequence and advantages of your construction
way.

In general, when you are making non-static member of class, compiler
assumed, that you need context of concrete object or you have no sence
to make non-static member of class.

3.
Let your virtual method of derived do not use any data of derived.
Note, the class of concrete derived object in general case is context
too, but in the case of ctor, compiler can know the real class of
creating object.

But how can you tell to compiler, that your desired virtual method do
not use any data of derived and can be called from base ctor? Do you
want to introduce new keywords for the short range of methods, which
are using only class of own object and able to be called from base
ctor?

What the sence of the language extention:
to be compatible with alredy existent code?
to eliminate unneccessary declarations and expressions?
to allow alternative external class behaviour?

No sence.

4.
Often you must _not_ allow direct access to member with the help of
"."(point) operator, like this:
class x{public: int a; };
x.a
Instead you can use function as access to data:
class x{public: int& get_a(){return a;} protected: int a; };
x.get_a();

In your case, if you are not creating object in the concrete class, you
can remove creation to derived and declare access method in base. This
is most flexible way, but take extra size and has execution time loss:

class Base
{
protected:
virtual RecordBase* FRecord()=0;
Base(){}
};

class Derived : public Base
{
protected:
RecordBase* _FRecord;
RecordBase* FRecord(){ return _FRecord; }

public:
Derived():_FRecord(new RecordDerived){}
~Derived(){delete _FRecord;}
};

5.
The second way is using parameter of ctor of Base class. The way is
similar to calling from base class virtual method of derived, which do
not use any data of derived except class of derived. This way do not
take extra execution time to access to data.

class Base
{
protected:
RecordBase* _FRecord;

Base(RecordBase* p=0):_FRecord(p){}
~Base(){delete _FRecord;}
};

class Derived : public Base
{
public:
Derived():Base(new RecordDerived){}
};

Note, now "Base" looks like kind of RAII wrapper for naked
"RecordBase*".

6.
In theory, if you need very complex algorithm, defined in derived, use
two-step initializing:

1. first set all data to state safe for destruction,
2. call correct method "create" of already properly initialized object

In order to create the objects with the help of single ctor, ( not as
here Derived obj; obj.create(); ) you can declare
two constructor in each base class:

1. initializer-ctor, having dummy parameter and calling base
initializing ctor
2. creater-ctor, calling base initializer-ctor and correct method
"create"

class Base
{
protected:
RecordBase* _FRecord;

//simple creator
virtual void create();

public:
//init-ctor
Base(RecordBase* p=0):_FRecord(p){}

//creater-ctor
Base(int,int):_FRecord(0){ Base::create(); }
~Base(){delete _FRecord;}
};

class Derived : public Base
{
protected:
//complex creator
void create();

public:
//init-ctor
Derived(RecordBase* p):Base(p){}

//creater-ctor
Derived():Base(new RecordDerived){}
//complex creater-ctor
Derived(int,int):Base(0){ Derived::create(); }
};
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top