79481450

Date: 2025-03-03 15:57:14
Score: 0.5
Natty:
Report link

Why Allow Declaration-Only Constructors?

If A were a base class, declaring A(); without defining it would force derived classes to provide their own constructor implementations, another reason is that declaring a constructor without defining it can be used to make a class non-instantiable like:

class A {
public:
    A(); // Declared but not defined
};

Any attempt to instantiate A will result in a linker error, effectively preventing object creation.

How to fix this error

class A {
public:
    A(){}; 
};
A arrayA[10];

Assembly Diffing

with the linker error snippet it outputs the following

arrayA:
        .zero   10
__static_initialization_and_destruction_0():
        push    rbp
        mov     rbp, rsp
        push    r12
        push    rbx
        mov     eax, OFFSET FLAT:arrayA
        mov     ebx, 9
        mov     r12, rax
        jmp     .L2
.L3:
        mov     rdi, r12
        call    A::A() [complete object constructor]
        sub     rbx, 1
        add     r12, 1
.L2:
        test    rbx, rbx
        jns     .L3
        nop
        nop
        pop     rbx
        pop     r12
        pop     rbp
        ret
_GLOBAL__sub_I_arrayA:
        push    rbp
        mov     rbp, rsp
        call    __static_initialization_and_destruction_0()
        pop     rbp
        ret

notice the call A::A() [complete object constructor] but there is no base object A::A() defined hence causing the linker error, while after applying the fix the following asm code gets added to the previous snippet:

A::A() [base object constructor]:
        push    rbp
        mov     rbp, rsp
        mov     QWORD PTR [rbp-8], rdi
        nop
        pop     rbp
        ret
Reasons:
  • Long answer (-1):
  • Has code block (-0.5):
  • Contains question mark (0.5):
  • Starts with a question (0.5): Why
  • Low reputation (1):
Posted by: w1redch4d