0

I found out that if you put the function defintion outside of the class, but within the .h file, a Linker error will be thrown as the function is already defined in the main.obj. That makes sense. So, if I put the function defininition in the .cpp file of the class, the function will be deined within the class.obj. That makes sense too. However, if I put the function definition WITHIN the class definition in the .h file, it works too. But in which .obj file is the function defined then?

Such as here:

#pragma once
class CTest
{
public:
    int Subtract(int x, int y)
    {
        return x - y;
    }

    int Add(int x, int y)
    {
        return x + y;
    }

};

So, is it going to be defined in the CTest.obj file or in the Main.obj file?

Thank you for your help.

Chiara
  • 1
  • 1
  • See dupe: [Why does the same class being defined in multiple .cpp files not cause a linker multiple definition error?](https://stackoverflow.com/questions/57516685/why-does-the-same-class-being-defined-in-multiple-cpp-files-not-cause-a-linker) – Jason Nov 22 '22 at 14:28

1 Answers1

0

In all of them. It's the linker's job to detect the multiple definitions and collapse them. A compiler might (and probably will) optimize this by only emitting the definition in TUs where the function is actually used.

Which is part of the reason why functions defined in headers are bad for compile time.

Sebastian Redl
  • 69,373
  • 8
  • 123
  • 157