Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I have to mention private methods in the header file of a class?

For now I do not use header files at all. Classes are each in a single .cpp file completely. But to save compile time I want to make use of header files now. My hope is that Visual Studio won't compile classes which weren't modified for debug builds then.

Is there a way to mention only public methods and members in the header file. In theory that would be enough information for the compiler. If another file, say main.cpp includes the class header there is no need for private methods and members, is it?

How can I use header files without retyping the names of private methods and members? The reasons for me to want so is coding productivity. When I want do add a small helper function to the class used by another method, I don't want to have to also add it's signature to the header file.

like image 793
danijar Avatar asked Apr 06 '13 09:04

danijar


2 Answers

If another file, say main.cpp includes the class header there is no need for private methods and members, is it?

No, public methods and members aren't necessarily enough. For example, if another .cpp file were to try and create an instance of your class:

SomeClass instance;

the compiler will need to know, among other things, how much memory to allocate for SomeClass. For that it requires full knowledge of SomeClass's private data members.

The way you are framing the question makes it sound as if you were intent on fighting the language. I don't think that's a good way to go about it. I think the best way is to do things the way things are usually done in the language of your choice, and depart from that only when there is a specific, clearly understood need.

The way things are usually done in C++ is that the entire class declaration goes in the header file, and the definition is in some way split between the header file and the corresponding .cpp file. The exact split is determined by various technical considerations. For example, templates and inline functions normally have to appear in the header file. On the other hand, placing code in header files increases dependencies and potentially build times.

There are ways to address these issues. However, since this involves extra complexity, I'd argue that this should only be done if there is a clearly identifiable need.

like image 86
NPE Avatar answered Oct 23 '22 06:10

NPE


I don't know of a way to do what you're asking, but there is another way to give some isolation. You might want to take a look at the pimpl idiom as it offers isolation about private information. It's a little bit of extra work, but it can be extremely useful, especially in large projects.

like image 4
John Szakmeister Avatar answered Oct 23 '22 07:10

John Szakmeister