Inner, Outer, Shake it all abouter

2009-07-29, , Comments

C++ programmers enjoy three levels of access control: private, protected and public. Some programmers use protected instead of private just in case someone might want to derive from their class some day. Others keep everything as private as possible, hiding nested classes in anonymous namespaces; these inner classes never seem to work quite the way you’d want, but if you get tangled up a friend can cut through the knots!

Python is less sophisticated. Prefix class members with a double underscore and their names are disguised to the world outside. Prefix module members with a single underscore to indicate they won’t be exported from that module. Many Python programmers use single underscore prefix in classes too (no mangling but better looking).

ACCU Button

Once you’ve used Python for a while you may well question the benefits of the C++ model. Recently a C++ question came up on the accu-general mailing list. It involved nested classes, operator<<() and code which refused to compile. You’ll have to trawl through the list archives if you want the exact question: I didn’t give it much attention since it seemed an example of the kind of struggle with the language which causes me to throw in the towel. I would like to quote from one of the answers though.

Surely your issue is that f() is a friend of Inner only. f() is not a friend of Outer. Inner is private to Outer. Therefore in the global scope, outside Outer, f() cannot access Inner via Outer::Inner, as that is private.

Wow, some brain twister!

Giant Klein bottle and Cliff Stoll

Time to get back to basics.

Encapsulation is about allocating responsibility and easing utility rather than protecting data, which is a side effect. — @KevlinHenney


My thanks to Jason McGuiness for allowing me to quote from his expert answer to a tricky C++ question. The photo shows Cliff Stoll holding the world’s largest glass klein bottle, which was produced by the company he owns, operates and mismanages, Acme Klein Bottles. Klein bottles get a mention here because they don’t have an outside or an inside, they just have a side. You can solve every computing problem with an extra dimension, except the problem of too many dimensions.