🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: comp.std.c++
Article #2510

Re: Why allow virtual function calls in constr

#2510
From: Wil Evers
Date: Fri, 10 Nov 1995 19:59
56 lines
2519 bytes

In article <199511071556.QAA12601@logatome.micronet.fr> verec@micronet.fr  
(Jean-Fran\gois Brouillet) writes:

> Hmmm! The question doesn't seem to be why virtual functions calls are
> not allowed in ctor/dtors, but why there isn't any kind of sepcial
> virtual functions which *could* be allowed to be called in such a
> context.
> 
> Standard, "ordinary" virtual function would behave as usual, but a
> special form of them, introcudced with an apropriate keyword would tell
> the compiler "Hey, I know what I'm doing, and I take personal
> responsability for not  using any field not defined in the first
> base-class which declared me".
> 
> What about using a "constructor" keyword, meaning both "virtual" and
> "can be called by ctors/dtors in any derived class" ?

If the member function to be called does not use any field not defined in  
the first base-class which declared it, it can - and should - be defined  
in that base class. If you have a set of such member functions from which  
one is to be selected depending on the derived type of the object under  
construction, you can pass a pointer to such a member function from the  
derived constructor's initializer list to one of the base class  
constructors:

class Base {
protected :
	void calledForDerived1();
	void calledForDerived2();
	Base(void (Base::*pf)()) { pf(); }
};

class Derived1 : public Base {
public: 
	Derived1() : Base(calledForDerived1) { }
};
	
class Derived2 : public Base {
public :
	Derived2() : Base(calledForDerived2) { }
};

I don't particularly like this because I distrust constructors whose  
functionality is tightly coupled to a derived class. But if you really  
need such a thing, this technique is certainly less confusing than  
introducing yet another keyword complicating the language rules for  
virtual function call resolution.

- Wil

---
[ comp.std.c++ is moderated.  Submission address: std-c++@ncar.ucar.edu.
  Contact address: std-c++-request@ncar.ucar.edu.  The moderation policy
  is summarized in http://dogbert.lbl.gov/~matt/std-c++/policy.html. ]
Technical Details
Message-ID: <1995Nov10.102122.1652@ittpub>
Path: arc1-ca.pugleaf.net!128.32.155.1!matt
References: <199511071556.QAA12601@logatome.micronet.fr>

Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!128.32.155.1!matt
From: wil@ittpub.nl (Wil Evers)
Newsgroups: comp.std.c++
Subject: Re: Why allow virtual function calls in constr
Date: 10 Nov 1995 19:59:22 GMT
Organization: <none>
Approved: matt@physics2.Berkeley.EDU (Matt Austern)
Message-ID: <1995Nov10.102122.1652@ittpub>
References: <199511071556.QAA12601@logatome.micronet.fr>
NNTP-Posting-Host: physics2.berkeley.edu