14

Can static function access non-static members of class?

 2 years ago
source link: https://www.programmerinterview.com/c-cplusplus/can-static-function-access-non-static-members-of-class/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Can a static function access non-static member variables of class?

The answer here is no. What is the reason? Well, because non-static member variables of a class always belong to an object – meaning that every object has it’s own personal copy of non-static member variables (also known as instance variables). And, static functions have no object to work with since they belong to the class as a whole. Remember that you can call a static function without an object – and for that exact reason a static function can not call instance variables. For example, the following code will not work:

class Stocks
{

  int number;

  static void picker( )
  {
     /* this is not allowed because picker is a static 
        function and can not access an instance variable
     */  
     number = 6;
     ...
  }


}

Do static functions have a “this” pointer?

No, they do not. Because a static function can be called without using an object, the “this” pointer is not passed into the function. Remember that the “this” pointer is only used when a class is instantiated as an object.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK