Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linker error for different declarations of default constructors

Tags:

c++

c++11

c++14

I have been playing around with default constructors and noticed a weird behavior (from my point of view).

When I declare A() = default, I get no linker error.

struct A
{
  int a;
  A() = default;
};

A a; // no linker error

However, when I declare A(); I get it.

struct A
{
  int a;
  A();
};

A a; // linker error - undefined reference to `A::A()`

Questions:

  1. What's the difference between the two?

  2. And if A(); produces a linker error, why is it supported in the first place? Any practical applications?

UPDATE (Follow-up Question)

For A(); why can't it be implicitly defined by the compiler if no definition is specified by the user?

like image 274
Joseph D. Avatar asked Oct 17 '25 19:10

Joseph D.


1 Answers

In the first case the compiler itself defines the constructor. Take into account that in the first case the constructor declaration is at the same its definition.

In the second case as the constructor is a user-defined constructor then it is the user who must to define the constructor. In the second case there is only a declaration of the constructor.

Take into account that you can declare a constructor and then define it using the specifier default.

For example

#include <iostream>

struct A
{
    int a;
    A();
};

A::A() = default;

int main() 
{
    A a;

    return 0;
}
like image 130
Vlad from Moscow Avatar answered Oct 20 '25 09:10

Vlad from Moscow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!