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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With