Pipsqweek
Pipsqweek

Reputation: 404

Confused on the locations of class declaration and implementation in c++

I have not been able to find the specific answer to this -- I do know that .h files contain class declarations and .cpp files hold the implementation.

I am confused as to how this is done without repetition.

If I have a class Animal it might be called in several areas of the program. So it would seem I would have to re-write the implementation several times (which no doubt means I am misunderstood).

It seems a bit goofy to include a .h declaration and .cpp implentation with every use of the given class (evidence I am misunderstanding something as well).

Where have I gone wrong in the subject of separating declaration and implementation?

I've been doing PHP and Python all of this time, so it might be prior habits confusing me.

Upvotes: 2

Views: 136

Answers (1)

Quentin
Quentin

Reputation: 63144

.cpp files are compiled once into object (.o) files.
They are never included into other .cpp files (that would lead to multiple definitions, which are an error in the general case).

Declarations, which are generally retrieved by #includeing header files, are how one .cpp file can know what's defined in some other .cpp file and use it without actually having its definition.

Once all of the .cpp files have been compiled into object files, the linker comes along and links all the object files together to form the final executable or library.
If multiple definitions of the same thing are found, or if one is missing, that's a linker error.

Upvotes: 5

Related Questions