Why is it that a major class should be defined in a header file, then given a source file to define it's functions?

Recommended Answers

All 3 Replies

One good reason would be to hide the implementation. If any changes need to be made to the implementation then it makes sense to separate it into a single file so that any code that uses the header doesn't need to be recompiled. If you place declarations in a header file you can more easily break the one definition rule, so separating declarations and definitions will make writing correct code easier. If you place the entire class in your headers then compilation can also take longer.

Thanks. Here's another question that came to mind. When you have more than one source file, how are they typically compiled? Does it compile the file with main in it first? Does it compile them in alphabetical order? Or something different?

And what's the one declaration rule?

It depends on the compiler. Generally the files will be compiled in the order that they're listed when the compiler is run.

>>And what's the one declaration rule?
One "definition" rule. It means that you can declare an object as much as you want because a declaration only says "Hey, I exist", but you can only define it once because a definition actually makes the object exist by allocating memory and calling constructors. If there are multiple definitions then you'll get an error.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.