473,659 Members | 3,605 Online
Bytes | Software Development & Data Engineering Community
+ 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::Derive d()
: 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::Create Record exists yet.
Obviously, I could re-write my constructors like this:

Base::Base()
{
}

Derived::Derive d()
: 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 2618
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::Derive d()
: 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::Create Record exists yet. Obviously, I could re-write my
constructors like this:
Base::Base()
{
}

Derived::Derive d()
: 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.********@com Acast.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::Create Record 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.ne twrote in message
news:45******** *************** @news.newshosti ng.com...
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::Create Record
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():_FRec ord(new RecordDerived){ }
~Derived(){dele te _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(RecordB ase* 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
3083
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 for derivedOne to explicitly declare the other 3 as pure virtual methods?
4
4611
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
21716
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. Dev
4
12872
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 C# 3.0? Any comments? Néstor
4
4333
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 Methods?
15
12779
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" ); } } class MyClass :ThirdPartyClass, IDisposable { void IDisposable.Dispose() {
7
3406
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 class is derived as virtual? How does the order of construction/destruction is impacted if the base class is derived as virtual or non virtual? just see the example below.
10
1593
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 class. So I have something like this: class Base { private: virtual std::string GetString() const = 0;
13
4917
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
8428
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8337
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8748
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8531
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8628
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7359
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6181
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
2
1978
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1739
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.