As far as I know it is not possible to call the constructor of the base class. The only way I know is this:
MyClass::MyClass(/* args */) : Base(/* args */)
{
// ...
}
but this would invoke the constructor at the beginning. Is there any way to call it somewhere else in the constructor? Something like this:
MyClass::MyClass(/* args */)
{
// ... instructions
Base::Base(/* args */);
// ... other_instructions
}
According to this What are the rules for calling the superclass constructor? question I understand there is no way but I read here and I guessed it was possible, but if I try I get:
error: invalid use of 'class Base'.
Am I doing something wrong? Is it possible to do this some way or is there any other possible solution to this need?
Thanks!
EDIT: I understand I forgot a key point: the base class is part of a framework, and therefore it would be good not to have to modify it, if possible.
The base class is always fully constructed before construction of your own class begins. If you need to make a change to the state of the base class, you have to do that explicitly after it has been constructed.
Example:
No, you can't do it that way, as other have described in their previous answers.
Your only chance is composition, IOW that
MyClass
usesBase
class as a member field:so you can initialize
_base
later, when you have the needed info. I don't know if this can apply to your scenario, anyway.Besides the already written solutions, you can also use a static constructor function and make the contructor of
MyClass
private.Now you would have to create instances of
MyClass
either as:or
no, because it will not be type safe.
consider you have: a class
A
and a variableA.var
.now consider
B
inherits fromA
, and usesvar
beforeA
was initialized. you will get a run time error! the language wants to prevent this, thus superclass constructor must be initialized first.No. It is not possible, because the order of constructor calls is strictly defined by the standard. Base class ctor has to be executed before the derive class ctor can be executed.
Use the base-from-member idiom to run your code before the ctor of the "real" base class (which is Base):
This works even if you don't have actual members you want in DerivedDetail. If you give more specifics on what you must do before the Base's ctor, then I can give a better example.