Search code examples
c++default-constructor

Is it possible to make a C++ type that mimics the constructor semantics of fundamental types?


The constructor semantics of int/double/etc. are:

int a; // uninitialized
int b = int(); // zero initialized
int c = int(4); // four

Is it possible to define a class with exactly the same behavior? I.e., one that has both uninitialized and initialized default constructors? I believe this is impossible, and currently work around it by making a constructor that compiles only when called with 0, but want to make sure there isn't a way to exactly mimic fundamental types.


Solution

  • If no constructors defined:

    struct A { int x; };
    
    A a; // default-initialized (unintialized)
    A b = A(); // value-initialized
    A c = { 4 }; // four