-1

I am new to c++ and trying to understand the one-definition-rule. Will including the below test.h file in multiple c++ files voilate the one definition rule (syspath and tags). If not why not ?

 #ifndef TEST_H
 #define TEST_H_

#include <string>
#include <unordered_set>

namespace X {

class Test {
  public:
     // Default constructor.
     Test();
     ~Test();

     const std::string& syspath() const { return syspath_; }
     const std::unordered_set<std::string> tags() const { return tags_;}
   private:
     std::string syspath_;
     std::unordered_set<std::string> tags_;
};

}  // namespace X

#endif  // TEST_H_

2 Answers2

2

syspath and tags are not objects or non-inline functions, so the ODR does not apply to them. The ODR for types applies indirectly to them (as they're part of the type X::Test), but as long as they (and X::Test) are identical in every compilation unit, they're fine.

As the wikipedia page notes, there are two related but different parts of the ODR -- one that applies to templates, types, functions and objects within a compilation unit and one that applies to objects and non-inline functions across compilation units.

Chris Dodd
  • 119,907
  • 13
  • 134
  • 226
1

ODR allows multiple definitions of a class as well as definitions of inline functions as long as all definitions are the same, and each definition is in a separate translation unit. The latter requirement is satisfied by the header guards (or it would be if there wasn't a typo).

A class definition merely declares data members. These are not variable definitions. ODR allows unlimited declarations.

No instance of a member variable exists until an instance of the class is constructed, and each instance of the class contains a separate instance of the variable.

There are no violations of ODR if this header is included in multiple translation units.

eerorika
  • 232,697
  • 12
  • 197
  • 326