codingdir logo sitemap sitemap |
Home
PHP
C#
C++
ANDROID
JAVA
JAVASCRIPT
PYTHON

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


By : , Category : c++

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)) {}
}
ReLated :

It should be

A::A(std::string s, int i) : _plantName(s), _growTimeMinutes(i) {

}

for example

supposing the variables _plantName and _growTimeMinutes are declared within class A or one of its superclasses. s and i are the constructor parameters for class A, the initialization will then call the string-constructor for _plantName with argument s and the int-constructor for _growTimeMinutes with argument i, thus initializing both variables.

Initialization lists are especially needed if you want to initialize const references. The assignment within a constructor would not work.

Hope I could help

This initialization:

s s1 = { 42 };

requires that s be an aggregate, or that it have a valid constructor taking e.g an int or an std::initializer_list.

When you add a member initialization at the point of declaration, you render your class s a non-aggregate, so you can no longer use aggregate initialization.

You could use the same initialization syntax for your non-aggregate by adding a constructor:

struct s
{
    s(int i) : i(i) {}
    int i=0;    
};

I believe this restriction has been relaxed for C++14.

See What are aggregates... for more information.

If you have VS2013 or another modern compiler:

A():min {false}, max {true} { }

avoids the problem because min(a,b) is a function-style macro and { can't start its argument list.

This is specific to initializer lists, so I've reopened the question. The "duplicate" suggested addresses macro use in expression context, which is fundamentally different - you can use (min) there.

You can still use the member initializer list:

Game::Game()
    : window_(SDL_CreateWindow(...), SDL_DestroyWindow)
{
}
Comments


Message :
Login to Add Your Comments .
How to disable registered OpenCL platforms on Windows?
Is Observable broken in Angular 2 Beta 3?
Cross-thread operation not valid when using Invoke
How to pass an IEnumerable or queryable list of properties from Controller to View
Finding numbers after a certain keyword using Python
Pocketsphinx recognizes random phrases in a silence
Passing non-thread-safe objects through thread-safe containers
React scroll nav
BizTalk WCF-BasicHttp Adapter does not allow Empty string for Service Certificate Props
Why property ''cause" of Exception is repeating forever?
Privacy Policy 2017 © codingdir.com All Rights Reserved .