473,467 Members | 1,565 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

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 2596
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");
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...

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.