Can static variables of a class be accessed and modified by any member function?

Can static variables (of a class) be accessed and modified by any member function (static/otherwise) of that class?

Also, what are the typical instances of having a static function in a class?

When we say a data member is static, it means there is only oneinstance of that data member for all instances of that class.

Access control on static members is no different than access controlfor any non-static member; i.e., they can be private, protected or public.

All member functions (static or otherwise) can access the static members ofthe class they belong to without special qualifications.

Any non-member function, including global functions and members of otherclasses, can only access static members through an object of the class it belongs toor by using the fully qualified name of the static member.

Here is an example:

class static_test{public:	static int i;	void foo ()	{		i = 10;	}	static int bar 	{		return i;	}};void foo ( static_test t){	t.i; // access through object of type static_test	static_test::i; // access through fully qualified name}
Use static members whenever you want to express a concept or behaviorthat is common to all the objects of a class or is a property of theclass rather than any given object. Static members are also used to keeptrack of instances of classes, like counting them or preventing multiple copiesof an object, etc.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin


Recent Articles: