C++ pointer-to-member syntax

When reading Bruce Eckel’s TICCP volume 1 and doing an exercise on pointers-to-member syntax, I was reminded of one thing I like about Lisp and even more about Scheme: simple syntax. In comparison, C++ is so awful.

For e.g., Ex 25 in Ch 11 of Volume 1 asks us:

Create a class containing an array of int. Can you index through
this array using a pointer to member?

Well, here is the class:

class Foo {
int a[10];
Foo() {
for (int i = 0; i < 10; i++)
a[i] = i;

Now, how do I declare the pointer-to-member that will refer to a?

After several tries, I got it:
int (Foo::*mem)[10];, which I use like this:
mem = &Foo::a;

I’d tried:

int Foo::*mem;
mem = &Foo::a;


int Foo::*mem;
mem = &Foo::a[0];


int Foo::*mem[];
mem = &Foo::a[0];

(this crashed the compiler, GCC 3.4.4 on Cygwin)


int Foo::*mem[10];
mem = &Foo::a;

The point is that special syntax to do everything is so icky once you have tasted Scheme. I’d say half or more of Bruce’s book is about the syntax to get to the various features of the language. You are focusing so much on learning syntax that you don’t have any time to figure out how you’d use those features for real work. And with the convoluted syntax in your way, you are not likely to be using the appropriate feature where it would be really handy.

Nevertheless, TICPP does an excellent job of just that: describing the language’s features and trying to give a scenario where that feature would be useful. Too bad, knowing the features requires memorizing so much syntax. In C, to get to a “feature”, I’d just look at the man page for the relevant function. There are no man pages for syntax, unfortunately.

Post a comment or leave a trackback: Trackback URL.

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

%d bloggers like this: