In a project, I have class B
which is derived from class A
, where class A
has an inaccessible default constructor.
Class B
is set up as follows:
class B : public A
{
private:
void SetupFunction() { /*Crucial code*/ }
public:
B() : A(Value) {}
}
Supposing it is crucial for SetupFunction()
to be called during initialization before the A(Value)
constructor, how would I go about achieving this? Is it possible?
I'm using Code::Blocks 13.12
on Windows 7
Initializer List is used in initializing the data members of a class. The list of members to be initialized is indicated with constructor as a comma-separated list followed by a colon. Following is an example that uses the initializer list to initialize x and y of Point class.
In C++, global variables are initialized before main() starts. So as part of global object (oc) initialization, the C class constructor is called. The constructors are also like any other user defined functions. We called the user defined function from the constructor.
Whenever we create an object of a class, the default constructor of that class is invoked automatically to initialize the members of the class.
We have to call constructor from another constructor. It is also known as constructor chaining. When we have to call same class constructor from another constructor then we use this keyword. In addition, when we have to call base class constructor from derived class then we use base keyword.
You could make SetupFunction()
return the value that's then passed to initialise A
, e.g:
class B : public A
{
private:
int SetupFunction() { /*Crucial code*/ return Value; }
public:
B() : A(SetupFunction()) {}
}
Or use the comma operator if you don't want to change SetupFunction()
:
class B : public A
{
private:
void SetupFunction() { /*Crucial code*/ }
public:
B() : A((SetupFunction(), Value)) {}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With