Some C++ traps

Back to Programming techniques

This sections contains some C++ traps I encounter now and then.

Initializer list does not match a free template parameter

The trap is to think that an initializer list matches a free template parameter.

template <typename Type>
void f(const Type& that) {}

int main()
{
    // No matching function declaration.
    f({1, 2});
    return 0;
}

Explicitly defaulted default-constructor does not direct-initialize members

The trap is to think that using = default direct-initializes the members (e.g. integer to zero). Instead, it default-initializes the members.

class A
{
public:
    A() = default;
    int b;
}

int main()
{
    A a;
    // The return-value could be anything.
    return a.b;
}

Zero is implicitly convertible to a pointer

The trap is that the literal integer 0 is implicitly convertible to a pointer, while the other literal integers are not.

class A
{
public:
    A(int a) {}
};

class B
{
public:
    B(int* a) {}
};

void f(A) {}
void f(B) {}

int main() 
{
    // Ambiguous overload resolution.
    f(0);
    // Ok; f(A).
    f(1);
    return 0;
}