Click here to Skip to main content
15,399,959 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
here is my trivial question: what can this friend method GetBox() can do?

class CBox
{
   float x;
   float y;

   friend CBox* GetBox();
public:
   float getArea();
   CBox();

protected:
    static CBox* m_Ptr; //<== I added this new member!
}

CBox::CBox()
{
  m_ptr= this;
}

CBox* GtBox()
{
   return m_Ptr;
}


What I have tried:

I understand this function GetBox() return a pointer to CBox type object, but kind of thing can it do?


I may need a small use case to deepen my understanding on friend methods.
Posted
Updated 29-Aug-21 6:53am
v2
Comments
Rick York 29-Aug-21 12:38pm
   
See this documentation : https://www.cplusplus.com/doc/tutorial/inheritance/

It can access the private members CBox.x and CBox.y.
   
Comments
Southmountain 28-Aug-21 22:02pm
   
I see, it can access all data members, including protected data members too.
Southmountain 28-Aug-21 22:08pm
   
I updated my question, added a static int memeber...
Greg Utas 29-Aug-21 7:41am
   
A friend can either be another class or another function, and making it a friend allows it to access all protected and private members.
Southmountain 29-Aug-21 20:33pm
   
thanks for your knowledge. in essence, the friend function is a global function that specifically interact with this class.
Greg Utas 30-Aug-21 5:52am
   
This is my go-to site for C++: https://en.cppreference.com. A wonderful resource.
C++
static CBox* m_Ptr; //<== I added this new member!
CBox::CBox()
{
  m_ptr= this;
}

CBox* GtBox()
{
   return m_Ptr;
}


Is an absolutely bad idea!!!

Static member variables are global variables, so to speak, that are scoped by the class namespace.
There will be only one instance of m_ptr, regardless of how many instances of the CBox exists. And when you do
m_ptr= this;
you can see how you going to end up in a hot water. You better off rewrite your function as:

C++
CBox* GtBox()
{
   return this;
}
   
Comments
Southmountain 29-Aug-21 20:37pm
   
yes, it looks like static variable m_ptr only point to one instance.
so this static variable m_ptr is not necessary and can be removed?
steveb 30-Aug-21 0:35am
   
Yes. You can just return this pointer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900