Difference between nested class and befriending a derived class in base class

ぐ巨炮叔叔 提交于 2019-12-14 03:24:35

问题


What is the difference between creating class P with all members as private and befriending class B which is derived from P

class P
{
private:
        int i;
        friend class B;
};

class B: public P
{
public:
        void get()
        {
                cout <<i;
        }
};

int main()
{

        B obj2;
        obj2.get();
        return 0;
}

vs

Creating a class within a class so that nobody can use the hidden class(subclass) it would be easy for maintanence without having to worry about breaking someone elses dependent code.

In which situation do we choose which design from the above(or any other if any)?

This question is in continuation to the comment section of answer of Why would one use nested classes in C++?


回答1:


Don't do what you suggest: its bad design and there's a chance of circular dependencies. Use protected members instead.

class P
{
protected:
    int i = 42;
};

#include <iostream>

class B : public P
{
public:
    void get()
    {
        std::cout << i << std::endl;
    }
};

int main()
{
    B Bobj;
    Bobj.get();

    std::cin.ignore();
    return 0;
}


来源:https://stackoverflow.com/questions/51095742/difference-between-nested-class-and-befriending-a-derived-class-in-base-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!