There is a massive module in my project, it computes many data tasks, update UI, and is responsible for interaction style. I want to move the user interaction part to another viewer class, make the old module more lightweight.

The structure of the module class looks like the following snippet.

class Module
{
public:
    void Func1();
protected:
    void Func2();
    void Func3();

    Type var1;
    Type var2;
    Type var3;
};

Now let’s create another viewer class and split some functions and variables to it.
I use the key word friend for the variable m_Viewer in class Module because it has to access a few protected variables of Module by m_Module.

class Module
{
public:
    void Func1();
    friend class Viewer;
    Viewer *m_Viewer;

protected:
    Type var2;
};



class Viewer
{
public:
    void Func2();
    void Func3();

protected:
    Type var1
    Module *m_Module;
};

We can also add friend for Module in class Viewer, after that the class Module and class Viewer can access the members of the other side each other.

Note: if the Module object is a member of another class, it can’t access var1 by the following way.

class Controller
{
public:
    Module *m_Module;   
};

m_Controller->m_Module->m_Viewer->var1;

Because m_Controller is not friend class object of m_Viewer.

Categories: CPlusPlus

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments

Content Summary
: Input your strings, the tool can get a brief summary of the content for you.

X
0
Would love your thoughts, please comment.x
()
x