Solemn's Site
Never stopping to think if I should.
struct XXX redeclared with different access

Posted in Software Development on 22 Dec 2017 at 15:29 UTC

Today I was writing some C++ and wanted to add a private struct within a class for storing some data, but not just any struct - I wanted a private abstract base struct with a couple of implementations.

So I wrote something like this:

class Thing
{
	private:
		struct PrivateAbstract {
			struct A;
		};
		
		struct PrivateAbstract::A: public PrivateAbstract // <-- Line 8
		{
			
		};
};

That didn't compile, GCC gave me the following error and Google wasn't terribly helpful when I searched for it:

/home/solemnwarning/test.cpp:8:3: error: ‘struct Thing::PrivateAbstract::A’ redeclared with different access

Whats happening, is that the initial declaration of A inside PrivateAbstract declares PrivateAbstract::A as public, but only in the context of PrivateAbstract, it still wouldn't be valid for anything outside of the Thing class to use it.

The compiler sees defining PrivateAbstract::A in a private block in Thing as changing the protection (relative to PrivateAbstract) from public to private, which isn't allowed. Changing the code as follows fixed it in the way I wanted:

class Thing
{
	private:
		struct PrivateAbstract {
			struct A;
		};
		
	public:
		struct PrivateAbstract::A: public PrivateAbstract
		{
			
		};
};

Despite how it looks, PrivateAbstract::A is still private to Thing, it can use it, but nothing outside of it can.

Perhaps obvious to someone more experienced with C++, but it took me a long time to figure out exactly what was happening.


Comments

No comments have been posted

Comments are currently disabled