Static member function Vs non-static member function.
Was wondering whats so special about a static member function before I discovered two things.
1. A static member function can be accessed using two sytaxes.
class_name::function_name
OR
object_name::function_name
2. A static member function can only access static member variables (not only those that belong to its class, but also those that belong to other classes).
Now why is there such a restriction?
Rule 1 says that a static function can be accessed even without an object name. means it can be accessed even if no object of that class is declared. That being so, if that function is allowed to acces non-static member variables, what will it do? Let Roll_no be a non-static variable in a class named student. Lets consider a static function func that tries to access Roll_no. Now when func is called and there are no or more than one objects of class student are declared, whose Roll_no will it get ? Thats why this restriction.... A static member function can not access non-static member variables .

0 Comments:
Post a Comment
<< Home