Search code examples
c++reflectionconstantsconstruction

Can a C++ constructor know whether it's constructing a const object?


In C++, object constructors cannot be const-qualified.

But - can the constructor of an object of class A know whether it's constructing a const A or a non-const A?

Motivated by a fine point in the discussion regarding this question.


Solution

  • Actually, a constructor never constructs a const object. The object is not const during construction, in the sense that the constructor code is allowed to change the object. If you call methods from within the constructor - they will be the non-const variants of methods.

    Thus, in this code:

    struct A {
        int foo() const { return 123; }
        int foo()       { return 456; }
        A() { x = foo(); }
        int x;
    };
    
    int bar() {
        A a;
        return a.x;
    }
    
    int baz() {
        A const a;
        return a.x;
    }
    

    both fnctions, bar() and baz(), return 456 - according to all major compilers (GodBolt).

    What happens with the constructed object is simply not the constructor's business.