Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: C++
Expertise: Beginner
May 6, 1997

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

Question:
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?

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

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

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

Any non-member function, including global functions and members of other classes, can only access static members through an object of the class it belongs to or 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 behavior that is common to all the objects of a class or is a property of the class rather than any given object. Static members are also used to keep track of instances of classes, like counting them or preventing multiple copies of an object, etc.
DevX Pro
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date