CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 13 of 13

Threaded View

  1. #3
    Join Date
    Apr 2009
    Location
    Netherlands
    Posts
    91

    Re: Using friend classes can improve encapsulation

    Quote Originally Posted by laserlight View Post
    Why not post example code to illustrate the point that you want to make?
    Alright I'll try:

    Code:
    class World {
    public:	
    	
         World();
         void AddSettlement(std::string name, int x, int y); 
    private:
        std::map<std::string, TerrainSquare*> settlements;
        std::vector<std::vector<TerrainSquare>> terrain;
    };
    Code:
    class TerrainSquare {
    public:
    	TerrainSquare();
            Settlement* settlement;
    };
    Code:
    class Settlement  {
    public:
    	Settlement();
    };
    I have this class called World. A World has a terrain which is 2d vector of TerrainSquare objects. It's possible for a TerrainSquare to contain a settlement. However if I had to find a specific settlement I would have to iterate over the entire 2d vector and check if a TerrainSquare contains that settlement. Instead i'm also keeping a map of pointers to TerrainSquares which contain settlements, so I can easily find a specific settlement.

    You will understand that because of this there are alot of actions needed to properly create and add a settlement to the World. Because of this I want the World class to be responsible for creating settlement and properly initializing them and adding them to the World.

    The problem with the above version of the TerrainSquare class is that it all has to have public atributes and constructor in order to allow World to initialize it. I don't consider this good encapsulation as one could still go and create a TerrainSquare or Settlement objects without using the World class. To enforce the use of the World class to create TerrainSqaures and adding Settlements to them, I want to make constructors and attributes of these classes private and let them befriend the World class, thus improving encapsulation.

    Making the classes look like this:

    Code:
    class TerrainSquare {
    	friend class World;
    private:
           TerrainSquare();
            Settlement* settlement;
    
    };
    Code:
    class Settlement  {
            friend class World;
    private:		
    	Settlement();
    };
    I hope this clarifies the point I'm trying to make. I tried to only expose code that would illustrate my problem, because most of these classes have way more atributes and functions but I thought they werent needed to illustrate my point.
    Last edited by AlastrionaAdair; May 5th, 2009 at 06:43 AM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured