The daily ramblings …

C++ : Static

Posted in C++ General by akamal on January 26, 2007

Static data types can be accessed without the instantiation of the class in C++. Applicable for static functions too. A typical use of static members is for recording data common to all objects. E.g: We can use static data to record the number of objects created.

To access static member, we uses ::(scope resolution) operator. An example is shown below:

01#include <iostream>
02using namespace std;
03
04class Circle
05{
06private:
07	// Initially declare radius as type double and static
08	static double radius;
09public:
10	Circle() {} // constructor
11	static void setRadius(double var)
12	{
13		radius = var;
14	}
15	static double getRadius()
16	{
17		return radius;
18	}
19	static double getArea()
20	{
21		return radius * radius;
22	}
23};
24
25double Circle::radius = 30;
26
27int main()
28{
29	Circle circ;
30	cout << "Circle 1 radius is : " << Circle::getRadius() << "n";
31	// object circ can also access static method getArea
32	cout << "Circle 1 area is : " << circ.getArea() << "n";
33	Circle::setRadius(50);
34	cout << "Circle 1 radius is now : " << Circle::getRadius() << "n";
35	cout << "Circle 1 area is : " << Circle::getArea() << "n";
36	system("PAUSE");
37	return 0;
38}

From the example above, we don’t need to instantiate the class to access static method “method1”. So, that’s the plain use of static.

Remember the rules of thumb below:

1 – Static members can be called even when no instantiation of class is made. Normal members of class (non-static) can only be called when an object is instantiated out of the class.

2 – Static member / funcntion cannot have access to ‘pointer of the’ class. Meaning that pointer to a class will have its own members, and the static member won’t have access to that.

3 – Static member function cannot be declared virtual, while non-static member can.

4 – Static data members must be defined out side of class definition, because they don’t belong to any specific instance of the class.

01class X
02{
03public:
04	static int i;
05};
06// definition outside class declaration
07int X::i = 0;

5 – Static member functions get defined in the class and so should static member variables.

Advertisements

One Response

Subscribe to comments with RSS.

  1. Melina said, on December 20, 2007 at 4:26 pm

    very interesting. i’m adding in RSS Reader


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: