Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Private inheritance: name lookup error

I have the following code example that doesn't compile:

#include <stdio.h>

namespace my
{
    class base1
    { // line 6
    };

    class base2: private base1
    {
    };

    class derived: private base2
    {
    public:
        // The following function just wants to print a pointer, nothing else!
        void print(base1* pointer) {printf("%p\n", pointer);}
    };
}

The error that gcc prints is:

test.cpp:6: error: `class my::base1' is inaccessible

test.cpp:17: error: within this context

Now, i can guess what the problem is: when looking at the declaration of print, the compiler sees base1 and thinks: base1 is the base-class subobject of derived* this, but you don't have access to it! While i intend that base1 should be just a type name.

How can i see in the C++ Standard that this is a correct behavior, and not a bug in the compiler (i am sure it's not a bug; all compilers i checked behaved so)?

How should i fix this error? All the following fixes work, but which one should i choose?

void print(class base1* pointer) {}

void print(::my:: base1* pointer) {}

class base1; void print(base1* pointer) {}


Edit:

int main()
{
    my::base1 object1;
    my::derived object3;
    object3.print(&object1);
}
like image 424
anatolyg Avatar asked Apr 12 '11 11:04

anatolyg


1 Answers

The section you're looking for is 11.1. It suggests using ::my::base1* to work around this:

[ Note: In a derived class, the lookup of a base class name will find the injected-class-name instead of the name of the base class in the scope in which it was declared. The injected-class-name might be less accessible than the name of the base class in the scope in which it was declared. — end note ]

[ Example:
class A { };
class B : private A { };
class C : public B {
A *p;
// error: injected-class-name A is inaccessible
:: A * q ;
// OK
};
like image 176
Ben Stott Avatar answered Nov 14 '22 17:11

Ben Stott