C ++ Private Nested Abstract Class

So maybe this is a stupid question, and I think about it, but I have the following situation. I am making a "Shell class" that can run abstract objects of the Action class. This is the only class that should create or use these objects. Action objects must have access to the shell to perform certain actions on it, but I try to avoid adding public interfaces for this (no one should allow this).

I initially had a simple (not very elegant)

class Shell { public: bool checkThing(); // etc... private: bool _thing; }; class Action { public: virtual void execute( Shell &s )=0; }; class ChangeAction : public Action { public: void execute( Shell &s ) { // requires friendship or public mutator! s._thing = true; } }; 

So, I looked at the nested Action class, but I wanted to make it private (why let someone else do specific actions except Shell, right?)

 class Shell { public: bool checkThing(); // etc... private: bool _thing; class Action; }; class Shell::Action { public: virtual void execute( Shell &s )=0; }; class ChangeAction : public Shell::Action { public: void execute( Shell &s ) { // ok now! s._thing = true; } }; 

But, of course, I can no longer inherit from Action (which makes sense, it's private). So this will not work.

So my question is, should I just go with the first method, friendship or public interface? Can I use something similar to the second method to preserve this relationship with actions and shell? Do you have an idea?

+7
source share
2 answers

If the only code that should be able to see Action is Shell , one parameter would be to forward-declare Action in the header file, but only define the class in the .cpp file. This would allow you to declare as many Action subclasses as you would like in the implementation file without releasing any of the Action subclass, because someone else would not have a full class definition for Action . It also avoids the need for public interfaces or friend declarations - all Action classes are declared in the global scope, but are protected from other files by virtue of the declaration in the .cpp file.

Great question, by the way!

+3
source

You can use a combination of methods: basically just take all your classes from the first method and move them to the private section of the shell class:

 class Shell { public: bool checkThing(); // etc... private: bool _thing; class Action { public: virtual void execute( Shell &s )=0; }; class ChangeAction : public Action { public: void execute( Shell &s ) { // ok now! s._thing = true; } }; }; 
0
source

All Articles