473,288 Members | 1,745 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,288 software developers and data experts.

base class initialization via virtual methods

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
Jan 10 '07 #1
5 2588
Dennis Jones wrote:
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
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Jan 10 '07 #2

"Victor Bazarov" <v.********@comAcast.netwrote in message
news:eo**********@news.datemas.de...
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
Jan 10 '07 #3
Dennis Jones wrote:
>
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.
Jan 10 '07 #4

"Ron Natalie" <ro*@spamcop.netwrote in message
news:45***********************@news.newshosting.co m...
Dennis Jones wrote:
>>
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.
I know, Ron...that's why I asked the question.

- Dennis
Jan 10 '07 #5
Dennis Jones wrote:
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(); }
};

Jan 13 '07 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: qazmlp | last post by:
I have a base class('base') containing 10 public pure virtual menthods. I have a class(derivedOne) deriving from 'base'. derivedOne implements only 7 of those base methods. Now, is it a good style...
4
by: Xavier | last post by:
Hi, I have a question, in a "dreaded diamond" situation, regarding the following code: ---- Begin code #include <iostream> using namespace std;
8
by: Dev | last post by:
Hello, Why an Abstract Base Class cannot be instantiated ? Does anybody know of the object construction internals ? What is the missing information that prevents the construction ? TIA....
4
by: Néstor Marcel Sánchez Ahumada | last post by:
In a method declaration the 'sealed' keyword must be used with the 'override' keyword to avoid further overriding. Thus it can't be used in base classes. Why? This would be a good enhancement for...
4
by: Akhil | last post by:
Hi All, Can u please explain this. Base Obj = new Derived(); Can Obj access methods both of Base and Derived or what will be the behaviour? What will be the behaviour for Overridden...
15
by: jon | last post by:
How can I call a base interface method? class ThirdPartyClass :IDisposable { //I can not modify this class void IDisposable.Dispose() { Console.WriteLine( "ThirdPartyClass Dispose" ); } } ...
7
by: BeautifulMind | last post by:
In case of inheritence the order of execution of constructors is in the order of derivation and order of destructor execution is in reverse order of derivation. Is this case also true in case...
10
by: Dennis Jones | last post by:
Hello, I have a hierarchy of classes in which there will be a data element that is common to all descendant classes. This element (a string in this case) is constant, but specific to each...
13
by: Rahul | last post by:
Hi Everyone, I was just playing around virtual functions and landed up with the following, class Base1 { public: virtual void sample() { printf("base::sample\n");
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: marcoviolo | last post by:
Dear all, I would like to implement on my worksheet an vlookup dynamic , that consider a change of pivot excel via win32com, from an external excel (without open it) and save the new file into a...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.