c++classg++object-files

Why the Class definition does compile one way and not the other?


I simplified the code to 2 files compiled independently and linked together.

file: main.cpp

class A{
    public:
        int value;
        A(int);
};

#include <iostream>
using namespace std;

int main(int argc, char **argv)
{ A a{7};
    cout<<"a.value="<<a.value<<endl;
    return 0;
}

file: classA.cpp

class A{
    public: 
        int value;
        A(int x):value{x}{};
};

//A::A(int x):value{x}{}

From my understanding of the process, when classA.cpp get's compiled, a function "A::A" is created (a constructor of the Class). If I comment the line A(int x):value{x}{} and uncomment the commented one the result into the object file should be the same.

But in the first case the two object files do not link together, and in the other case they do link. Why is that ?

I checked the object file generated for classA and in the first case is empty, so it is normal that it won't link, But why ?


Solution

  • The definitions of the two As are different. One has an inline definition of the constructor and the other has not. This is not allowed and would cause undefined behavior if linking had succeeded.

    If you make the definitions exactly the same and then define the constructor non-inline:

    A::A(int x):value{x}{}
    

    Then the linkage will succeed and the program will have defined behavior.