Guillaume Racicot Guillaume Racicot - 5 days ago 5
C++ Question

Base class constructor not called?

I was searching the cause of a really strange bug in my program. I discovered that strangely, the base class constructor is not called for some reason. Here is the code to reproduce:

struct Parent {
Parent() : test{9} {}

int test;
};

template<typename T>
struct Child : T {
Child() = default;

// Will obviously not call this one
template<typename... Args, std::enable_if_t<sizeof...(Args) == 9999>* = nullptr>
Child(Args&&... args);
};

int main() {
Child<Parent> test;
std::cout << "This is a test: " << test.test << std::endl;
}


In my case, the program simply crash or print random values.

If I change the child class to this, the constructor is called:

template<typename T>
struct Child : T {
Child() = default;
};


Same thing for that, the constructor is still called:

template<typename T>
struct Child : T {
Child() {}

// Will obviously not call this one
template<typename... Args, std::enable_if_t<sizeof...(Args) == 9999>* = nullptr>
Child(Args&&... args);
};


But with the first definition, the parent constructor is not called. I even tried to mark the parent constructor as deleted, but it still compile and crash!

Here's the code with the deleted constructor:

struct Parent {
Parent() = delete;

int test;
};

template<typename T>
struct Child : T {
Child() = default;

// Will obviously not call this one
template<typename... Args, std::enable_if_t<sizeof...(Args) == 9999>* = nullptr>
Child(Args&&... args);
};

int main() {
Child<Parent> test;
std::cout << "This is a test: " << test.test << std::endl;
}


I'm using visual studio 2015 update 3.

Answer

Bug in that compiler.

If you upgrade your version of Visual Studio 2015 that should work.

Microsoft's online compiler at version 19.10.24631.0 (x86) appears to produce the correct output.

GCC 6.2.0 and Clang 3.8.0 also appear to produce the correct output

Comments