Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ cannot use same class as private base

I wonder why the following example does not compile: I have an ImageContainer class, which inherits from Image privately (so that, it's users should not know that it inherits from Image). This class also contains a list of images and has an AddImage function.

class ImageContainer: private Image {
public:
    ImageContainer (){};

    void addImage (const Image &img){
        //adds image to the container
    };

    std::vector<Image> images;
};

class DerivedImageContainer: public ImageContainer {
public:

    void init () {
        addImage (Image (background, Position(960, 533), Align::MiddleCenter));
    }
};

From a derived class (DerivedImageContainer) I want to call the addImage function, adding a new image to the list.

I was surprised to see that this does not compile. The error is:

error: ‘class Image Image::Image’ is inaccessible within this context

I am creating an Image that is absolutely not related to the ImageContainer's base class And I am not even touching the ImageContaner's internal stuff, I am only calling a public function. Why does the compiler complain?

Does this mean, that in derived functions we cannot use members, that have the same type as private-inherited-class, somewhere in the class hierarchy?

It does not work with g++ 4.8.2 and g++ 7.5.0

like image 513
Nuclear Avatar asked Jan 25 '23 22:01

Nuclear


1 Answers

Access checks are performed after name lookup. And the problem here is that of scope. Inside the scope of a class, unqualified name lookup proceeds from within it into its bases. And so it finds Image as the type name of a base. Then it must check the accessibility of this base. Hence the error.

The remedy is to not do unqualified name lookup. Specify Image by another way.

addImage ( ::Image (background, Position(960, 533), Align::MiddleCenter) );

::Image is the fully qualified name of the type at namespace scope. So it skips the lookup inside class scope.

like image 95
StoryTeller - Unslander Monica Avatar answered Jan 30 '23 08:01

StoryTeller - Unslander Monica