c++function entities — 2nd class citizens@@

Compared to java, I feel c++ is more flexible, “creative” and “loose” with functions; c++ weaves functions more into its rich syntax; and c++ apps rely more heavily on passable function entities. Any algorithm (any trivial body of code) can be passed around like a variable or object.

Inside the computer, a function (like objects) occupies a chunk of memory in “text” section, so it’s reasonable to pass its address to where it’s needed. C++ lets your *package* algorithms into passable function entities. These function entities are often stateless[2]. Consider functional programming. I call these 2nd-class citizen objects because they normally do not have state, variables, virtuals etc.

(Java Threads also should not but often have state.)

Java has interfaces and Method objects. C++ has func pointers and functor objects. Both designs are powerful, widespread and proven.

[2] functors are almost always pbclone in STL. Some functors are stateful — (beside generators) Dinkumware’s hash tables have hashing traits/policies as state in the hashing functors. See separate blog post.

http://www.newty.de/fpt/fpt.html#callconv shows some func ptr syntax examples —

someObject.someMethodReturningAFunctor()(arg1, arg2); // not the number of () pairs
(instance1.*pt2Member)(12, ‘a’, ‘b’);

(*this.*pt2Member)(12, 'a', 'b');     
(instance2->*pt2Member)(12, 'a', 'b');  

(*(someComplexExpressionReturningFuncPtr))(arg1, arg2)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s