C++ – The auto key word

A funny remark  which I discovered without realizing it ( Though I’m not the first one… ), is that the auto keyword can be used to access public members with private types, as so:

#include <iostream>
using namespace std;

class FooClass
    struct PrivateFoo
        bool m_bFoo;

    PrivateFoo m_Foo;

int main()
   FooClass foo;

   // The following code will produce an error,
   // you can't access the private type FooClass::PrivateFoo
   FooClass::PrivateFoo* fooPtr = &foo.m_Foo;

   // But this works
   auto fooPtrAuto = &foo.m_Foo;

   // Nothing fancy

   return 0;

So as you know, I can’t use the type PrivateFoo directly, because it’s declared as private, but the auto keyword is permitted, even though it detects the type needed and, well, uses it. I see why is technically is permitted, but, logically, it doesn’t give any sense for me, though it might be usable.

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s