Are \'private\' or \'public\' keywords in ANSI C (or any other C for that matter), or were they only added in C++ (and Java, C#, ...)?
Neither are C keywords, but some people do the following:
#define public
#define private static
For those who think it is a bad idea to do the above, I would agree. But it does explain why someone might think public
or private
are C keywords.
For those who think it won't compile in C, try this:
#include
#include
#define public
#define private static
private void sayHello(void);
public int main(void) {
sayHello();
return (EXIT_SUCCESS);
}
private void sayHello(void) {
printf("Hello, world\n");
}
For those who think it won't compile in C++, yes the above program will.
Well actually it is undefined behaviour due to this part of the C++ standard:
A translation unit that includes a header shall not contain any macros that define names declared or defined in that header. Nor shall such a translation unit define macros for names lexically identical to keywords.
So the example above and below are not required to do anything sane in C++, which is a good thing. My answer still is completely valid for C (until it is proven to be wrong! :-) ).
In the case of a C++ class with private members, you can do something similar (considered an abuse) like this:
main.c:
#include
#define private public
#include "message.hpp"
int main() {
Message msg;
msg.available_method();
msg.hidden_method();
return (EXIT_SUCCESS);
}
message.hpp:
#ifndef MESSAGE_H
#define MESSAGE_H
#include
class Message {
private:
void hidden_method();
public:
void available_method();
};
inline void Message::hidden_method() {
std::cout << "this is a private method" << std::endl;
}
inline void Message::available_method() {
std::cout << "this is a public method" << std::endl;
}
#endif