|
![](/i/fill.gif) |
Darren New <dne### [at] san rr com> wrote:
> Sure. But people are discussing .h files, where there's no such option in
> C++. In C, you could make the function static, but that's not the same thing
> for a C++ method.
How would you suggest having support for implementing private functions for
a class without having to declare them in the class declaration *and* without
opening the private parts of the class to any external code that wishes to
access it?
Assume you could do this in C++:
//-----------------------------------------------
// HeaderFile.hh
class MyClass
{
public:
void some_public_function();
private:
some_private_data;
};
//-----------------------------------------------
//-----------------------------------------------
// HeaderFile.cc
#include "HeaderFile.hh"
void MyClass::some_public_function() { ... }
// Add a new private function to MyClass:
void MyClass::a_private_function()
{
// Access some_private_data here
}
//-----------------------------------------------
Hey, that's great. I can add new private functions to MyClass without
having to modify the declaration of the class nor the header file. Cool.
Except for one problem:
//-----------------------------------------------
// SomeOtherFile.cc
#include "HeaderFile.hh"
void MyClass::bypass_privacy()
{
// Access some_private_data here
}
//-----------------------------------------------
Now you have opened your entire class for anyone to access from anywhere
without restriction, making your public/private distinction completely
meaningless.
(You might find that ok, but most OO programmers don't, including most of
the people who know about these things.)
The solution to this is to specify the private functions in the class
declaration.
If you don't care about privacy, then put everything in the public section
of the class and write all the formerly private functions in a nameless
namespace inside the source file. That way you don't have to add anything
to the header file if you want to add a new private function.
--
- Warp
Post a reply to this message
|
![](/i/fill.gif) |