Reputation: 5203
I want to be able to call a parameterised constructor of the base class AFTER I've done some calculation with the input parameters from the derived class constructor.
To what I believe, when you call a constructor of a derived class, the default constructor of the base class is called...
(unless its parameterised constructor is called specifically as so:)
DerivedClass(int a,int b) : BaseClass(a,b) {}
Is there anyway of doing something like:
DerivedClass(int a,int b) {
a += 2;
b += 5;
BaseClass(a, b); // <- this line I am questioning :(
}
And I assume what is above doesn't work because the default constructor of the BaseClass
is already been called..
Upvotes: 1
Views: 355
Reputation: 56557
No, you cannot defer calling a base constructor in a derived constructor. The only way to call a constructor is via the constructor initialization list, which is executed before the body of your constructor. If otherwise, you'd see probably lots of nightmarish code, where the base part of an object is not yet constructed but the derived part is trying already to initialize itself...
In your case, you can just do
DerivedClass(int a,int b) : BaseClass(a + 2, b + 2) {}
PS: You have an error in your code, when you call the BaseClass
you shouldn't use BaseClass(int a, int b)
, but only BaseClass(a, b)
, as it is a function call and not a declaration.
Upvotes: 4
Reputation: 54325
You cannot defer the base constructor but you can use functions.
For example:
DerivedClass(int a, int b) : BaseClass(adjust_a(a), adjust_b(b)) {}
Upvotes: 2