开发者

Does functions of a C++ class have only one copy for all objects?

Does the normal functions (and not the static ones) have only one copy for a class in C++, meaning tha开发者_如何学Ct all the objects refer to the same copy. If so what is the difference between normal function and static function. Also, my teacher was saying that we cannot call static functions of a class using "(object_name).(func_name)" notation but have to call it using the "class_name::(func_name)", while I understand that this is the logical thing to do, but as far as the language is concerned, am I not allowed to call a static function using (object_name).(func_name) notation? Finally, cannot I initialize the static data members of a class in the constructor of the class or inside any other function of that class, but have to do so from outside the class?


If by only one copy you mean all functions have the same location in memory, then yes, you are right. The difference is that static functions don't require an object to be instantiated in order to be called. This also implies that you can't access other non-static members of the class.

As for the initialization, you can't do it in the constructor since calling a static function that would access a static member would need the constructor to be called beforehand. There's no way to guarantee that. You can change the static inside the constructor, but it must be initialized elsewhere.

Think about this scenario:

class A
{
static int x;
public:
   A()
   {
      x = 3;
   }
   static int getX()
   {
      return x;
   }
}

int main()
{
   A::getX(); //what would x be here? It hasn't been initialized since A() was not called.
}

As for calling the function with (object).(function) instead of (class)::(function), I believed you are allowed to do it, but why would you?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜