Translation unit and classes

Started by
9 comments, last by ryt 5 years, 7 months ago
2 hours ago, fleabay said:

Please tell me what you think the purpose of include guards are in header files if there is no problem with multiple declarations of the same class in a translation unit.

Include guards are used to prevent cycle inclusion, not to (and not need to) prevent multiple declarations (not definitions). Though as frob said, most class declarations are also class definitions so they can't be multiple in one translate unit.

Here is an article on declaration vs definition.

https://www.kbasm.com -- My personal website

https://github.com/wqking/eventpp  eventpp -- C++ library for event dispatcher and callback list

https://github.com/cpgf/cpgf  cpgf library -- free C++ open source library for reflection, serialization, script binding, callbacks, and meta data for OpenGL Box2D, SFML and Irrlicht.

Advertisement
4 hours ago, fleabay said:

Thanks frob and wqking. I have been thinking that the implementation of an 'average' class in the .cpp class file was the definition. It seems very odd to me that both the declaration and the definition of a class are usually in the header.

I wouldn't say usually. The main advantage of it is so the compiler can inline. However you will quickly run into trouble doing that when you have class objects referencing each other. Also it doesn't really help you much with virtuals unless the copiler is doing some fancy optimizations and inlining them. In general I only put function definitions in the header when I want them inlined.

Here is some good explanation that I found:
 

Quote

Doesn’t defining a class in a header file violate the one-definition rule?

It shouldn’t. If your header file has proper header guards, it shouldn’t be possible to include the class definition more than once into the same file.

Types (which include classes), are exempt from the part of the one-definition rule that says you can only have one definition per program. Therefore, there isn’t an issue #including class definitions into multiple code files (if there was, classes wouldn’t be of much use).

Doesn’t defining member functions in the header violate the one-definition rule?

It depends. Member functions defined inside the class definition are considered implicitly inline. Inline functions are exempt from the one definition per program part of the one-definition rule. This means there is no problem defining trivial member functions (such as access functions) inside the class definition itself.

Member functions defined outside the class definition are treated like normal functions, and are subject to the one definition per program part of the one-definition rule. Therefore, those functions should be defined in a code file, not inside the header. The one exception for this is for template functions, which we’ll cover in a future chapter.

 

This topic is closed to new replies.

Advertisement