Search code examples
c++defaultdefault-constructor

Default nullptr pointer in class ctor give unresolved external symbol c++


I have the following class (not real names):

class CObject1 : public IObject1
{
public:
  CObject1(IObject2 *pIObject2 = nullptr);
}

Where the "I" versions are for interface classes. Now, when I create an instance of CObject1 as:

CObject1 object1;

I get an unresolved external symbol, complaining about CObject1(void) not being found. If I try to explicitly declare another ctor as:

CObject1()

I then obviously get the "multiple default constructors specified" warning, as one would expect.

Why can't the program find my default ctor??

Thanks in advance.

EDIT: Additional notes:

  • The interface itself does not have a ctor explicitly defined.
  • All of this is under the same namespace. I.e. the interface definition, implementation and instantiation.
  • I'm seeing this in MS Unit Testing. I don't have a "normal" project I can test this on.

Solution

  • Your class does not generate a default (CObject1()) constructor. What it generates is a constructor that requires one argument, and any code that reads the definition will know to populate that argument if it encounters what would otherwise be a default ctor - which is done at the call site.

    class C {
    public:
      C(int* p = nullptr);
    };
    
    C fn() {
      C c{};
      return c;
    };
    

    Generates

    fn():                                 # @fn()
            pushq   %rax
            leaq    (%rsp), %rdi
            xorl    %esi, %esi   ; <<- injects the nullptr
            callq   C::C(int*)   ; <<- note which ctor is called
            popq    %rax
            retq
    

    However: the unit testing framework might not be seeing that definition and working with the requirement that your objects have a default ctor. In which case, you should consider writing:

    CObject1() : CObject1(nullptr) {}
    CObject1(IObject2 *pIObject2);