Ghost314 Ghost314 - 1 year ago 104
C++ Question

C++, do private functions really need to be in the header file?

I have always thought of header files as a sort of 'public interface' describing a class, in which case it would be better to keep private fields and functions in the cpp file.

I understand that private fields need to be in the header so that other classes can tell how much memory an instance of a class will consume, but it occurred to me as I was about to write a private helper function, that this function could be made static, in which case there was no need for it to be 'part of the class' at all, it could just as easily be a regular function in the class definition's .cpp file.

It then occurred to me that all private functions could potentially be re-written to be static by accepting pointers/references to class fields instead of expecting to be defined in the class.

This would eliminate the need to declare any private functions in the header file.

I do like to follow conventions so now I want to ask, is it considered an established convention in C++, that non-static private functions should be in the header file? What about static functions or static constants?

EDIT I'm going to put in some code to explain what I'm getting at:

header file:

#ifndef SOME_CLASS_H
#define SOME_CLASS_H

class SomeClass
int x;
void combineWithX(int y);


.cpp file

#include "SomeClass.h"

void someHelper(int* x)
*x = (*x) + 1;

void SomeClass::combineWithX(int y)
x += y;

note that
someHelper(int* x)
in the cpp file references the private member x in spirit, but not directly, and therefore does not need to appear in the header. I'm wondering if this sort of thing is considered 'bad style'

Answer Source

I agree that it is a problem that implementation details need to be exposed in a header file; it interferes with separation of interface and implementation.

Moving private helper functions to be free functions in the .cpp file (I presume that is what you meant by "static") won't work if those functions need to access private member variables.

You may be interested to look at the pImpl idiom (more)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download