Chutian said:
What's the best way to share data between classes?
This question is too general. In what form is the data? Do the classes that
share the data always want to share it? Is the data a compile-time constant?
And there are probably many more questions that one could ask.
What's the purpose of define a member function in a class as 'static'?
In essence, a static function is a class-wide function, meaning that it is
relevant to the class but not to any specific instance of the class.
Just
for it to access static member variables?
That's one possible use for it, though class instances can also access
static variables, so you don't have to write a static function to access
static member variables.
Is there any other reasons?
Many of them. There's a class of mine that has 15 static member functions
for various purposes. The class is the base class of a hierarchy of wrapper
classes for objects stored in a database. Most of the static functions
perform certain operations on the database directly, without having to
actually create a wrapper object. A couple of them lock and unlock a mutex
used to protect the database's integrity. The static functions are called by
non-static functions and can also be called publicly.
Here's a very simple use for a static function:
class Rectangle : public Shape
{
public:
// ..
static double Area(double length, double width);
double Area() const { return Area(mLength, mWidth); }
private:
double mLength;
double mWidth;
// other stuff
};
This Rectangle class might be primarily used in a graphics library, for
example, and might carry a lot of baggage not shown here (drawing resources
etc.). Obviously, a Rectangle object must know how to compute its area, but
should you have to create a Rectangle object just to do such a simple
calculation? Static functions allow you to do some operations that a class
should know how to do, but without having to do the unnecessary work of
creating an instance of the class beforehand. Also, non-static members can
use the same static functions to ensure consistency.
DW