Re: call base class constructor from derived class constructor
On Nov 5, 8:56 pm, Paul Brettschneider <paul.brettschnei...@yahoo.fr>
wrote:
Alf P. Steinbach wrote:
* James Kanze:
On Nov 5, 1:47 pm, Ron Natalie <r...@spamcop.net> wrote:
Rahul wrote:
While working with Java, i came across super() which passes
values to base class constructor from derived class
constructor. I was wondering if this could be implemented
in c++ by any mechanism as super is not supported by c++,
atleast by MS vc++ 6.0.
C++ is not Java. Contructors are automatically called in the
language-defined sequence in C++. You can not alter that NOR
can you call them directly.
That's true in Java as well, with the restriction that 1) you
can only have a single base class, and 2) members are either
basic types or pointers, and don't have constructors. The only
difference is the syntax you use to pass arguments to the base
class constructor. In Java, since there's only one, the keyword
super() is sufficient,
In most cases super() would be sufficient in C++ too.
And Visual C++ provides that as a language extension, '__super', relying
on ordinary overload resolution, see e.g. <url:
http://msdn2.microsoft.com/en-us/library/94dw1w7x(VS.80).aspx>.
To some degree one may simulate the effect of '__super' by typedef'ing a
'Base',
typedef MyBaseClass Base;
but in particular, when MyBaseClass is something like X<Y, Z, ...> it
makes you repeat the whole shebang.
'super' would have been a great addition to C++0x.
Especially since there's years and years of existing practice... ;-)
What's the advantage of the super-syntax over explicit
initialisation lists resp. scope resolution with "::"? All I
see is the danger of obfuscation in the case of multiple
inheritance. I wonder if this would justify another keyword,
especially a common one like super. But I don't do Java, so I
may be missing something!
Well, IIUC, what Alf is proposing is quite unlike the super in
Java (which corresponds to the C++ initialization list). What
he is proposing would be useful, in at least two cases. The is
precisely multiple inheritance, where you don't care which base
class provided the function. The other would be in the case Alf
mentions, where the base class "name" is actually a very complex
template instantiation. Not having to repeat it is a definite
advantage. More generally, using super probably enhances
readability: the important thing when you use it isn't that you
are using a class named Base, it's that you're using the class
from which this class (or one of the classes) derives. It
expresses intent more clearly.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34