Click here to Skip to main content
15,881,812 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi Everyone..

Am quite confused about static function. Here a little part program.

//Header.h
C++
class A
{
public:
        COtherClass m_var;  // Here COtherClass is different class & am creating instance variable called m_var.

protected:
        static void Display();
};


Anyhow i can access m_var in Display() function, by making Display() as non static function.
My question is: Can i access m_var in Display(static function) ??

//Header.cpp

C++
void A :: Display()
{
  m_var.GetDocument();  //GetDocument() is the method in COtherClass.
}
Posted

1 solution

No.

A non-static function receives the hidden 'this' pointer. When you write m_var.GetDocument();, the compiler reads this->m_var.GetDocument();.

A static function does not receive the 'this' pointer. So, when you try to use an instance (non-static) method, the compiler asks "Which instance?".

You can either make m_var a static member, or keep GetDocument() as an instance method.

Hope this helps,

Pablo.
 
Share this answer
 
Comments
Guru_C++ 29-Aug-12 8:49am    
Oh..! Thank you for the help..

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