Internal communication for C ++ private functions?

When I write object-oriented code in C, I usually put the definition of the structure along with public functions in the header file and implement the public functions in a separate .c file. I provide the static keyword for all the "private" functions for this class and implement them in a .c file. Public functions can then call private functions that belong to the same class. Private functions cannot be called externally thanks to the static keyword, so GCC can optimize many of these functions. They are often built-in, and the original function is completely removed from the output file of the object.

Now to my question: how can I do the same with C ++ classes?

Say I have a header file:

class A { int private_field; int private_function(); public: int public_function(); }; 

And my .cpp file:

 #include <iostream> #include "Ah" int A::private_function() { std::cin >> private_field; return private_field; } int A::public_function() { return private_function() + 4; } 

In the resulting object file, private_function remains a separate character, and public_function calls private_function (not built-in). I would like to give an internal private_function relationship, so the compiler can do the same optimization as using C. I tried with anonymous namespaces and static, but I can't get it to work the way I would like. How to do it right, is it possible? I am using GCC.

+7
source share
1 answer

Class members never have an internal connection. The Standard states (section 9.3):

The member functions of a class in the namespace have an external relationship. The member functions of a local class have no relationships.

So, if you want to create helper functions with internal communication, you must use a non-member.

 static int private_function(A* pThis); class A { int private_field; friend int private_function(A* pThis); public: int public_function(); }; 

and then

 #include <iostream> #include "Ah" static int private_function(A* pThis) { std::cin >> pThis->private_field; return private_field; } int A::public_function() { return private_function(this) + 4; } 

Note this rule from the Standard (section 11.3):

A function declared in a friend declaration has an external binding. Otherwise, the function retains its previous relationship.

+8
source

All Articles