3

If I have a header file in which I want to declare a class:

class Entity
{
 int a;
 int b;
 void do_something();

};

Then this is just a normal declaration, right?

class Entity
{
 int a = 0;
 int b;
 void do_something();

};

But now does this turn it into a definition? If it does, what exactly happens when I try to include that header file into two .cpp files? I'm basically going to have two Entity classes defined in two files but is this okay? If it is okay, then why is it okay? What exactly is the linker going to do?

Jeff Schaller
  • 2,352
  • 5
  • 23
  • 38
yaelreshet11
  • 131
  • 5
  • 4
    Not really sure what you're asking, here. `class foo {};` is a *definition* of the `foo` class. `class foo;` is a *declaration* that `foo` is a class. – Adrian Mole Nov 02 '21 at 12:23
  • 1
    Does this answer your question? [Why does the one definition rule exist in C/C++](https://stackoverflow.com/questions/60085469/why-does-the-one-definition-rule-exist-in-c-c) – Quimby Nov 02 '21 at 12:23
  • 1
    Don't think the suggested duplicate is really relevant. More likely, a decent book would be a better place to which to be redirected. – Adrian Mole Nov 02 '21 at 12:25
  • @sag If you include the class definition into multiple compilation units you **do** get multiple definitions of the class. This isn't a declaration. – IInspectable Nov 02 '21 at 16:04

1 Answers1

1

Then this is just a normal declaration right?

class Entity
{
 int a = 0;
 int b;
 void do_something();

};

Nope. this is a definition of the Entity class, which includes a declaration of the do_something() method.

I'm basically gonna have two Entity classes defined in two files but is this okay? And if it is okay why is it okay?

This is ok because the One Definition Rule allows for classes to be redefined in multiple translation units as long as the definitions are the same.

You can think of it as all class definitions having an implicit inline.