Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Calling a function before base-class initialization in the initialization list

The Scenario:

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

like image 803
Bryn McKerracher Avatar asked Oct 26 '15 04:10

Bryn McKerracher


People also ask

What is initialization list in C?

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.

What is initialized in a function before constructor?

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.

Which constructor will initialize the base class data member in C++?

Whenever we create an object of a class, the default constructor of that class is invoked automatically to initialize the members of the class.

How do you call a base class constructor from a derived class in C++?

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.


1 Answers

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)) {}
}
like image 81
Jonathan Potter Avatar answered Sep 25 '22 02:09

Jonathan Potter