Static Member Functions

As seen in the discussion about object orientation there can also be static member functions.

OO: Class operations <-> C++: static member functions

They also uses the keyword "static".

Usage:

  • When there is "only one"

  • When the function does not depend on any non-static class atttributes

  • For constructing pre-defined object.

Example:

class Color {
private:
  int red, green, blue;
public:
  static Color* createTTURed();
};

Color* Color::createTTURed()
{
  Color *c = new Color;
  c->red = 204;  
  c->green = 0;  
  c->blue = 0;
  return c;
}

Notes for static member variables:

  • Since they are part of the class they are allowed to use private member data.

  • However, they do not have an object with them. So they can only access static member variables directly, all others only if they have an object.

To use a static member variable use them as if they where in a namespace. From within the class this is unnecessary.

Example:

Color* c = Color::createTTURed();

Practice:

define a class "Location" that has the two member variables posX and posY. provide a static member function called "getOrigin()" that creates a new location with posX=0 and posY=0.

Show the class definition and the implementation for getOrigin(). Show an example of how this could be called.

class Location {
private:
  int posX,posY;
public:
  static Location* getOrigin();
};

Location* Location::getOrigin() {
  Location *l = new Location();
  l->posX = 0;
  l->posY = 0;
  return l;
}
...
Location *o = Location::getOrigin();

Intermission: So how do I call a method again?

Assume the follwing class definiton:

class Bla {
public:
  static int doSomething(bool really);
  string getName();
}

To call the static function, we have 3 options:

// Preferred way:
int i = Bla::doSomething(true);
// This works also, but I do not like it.
int i = b->doSomething(true);  // Assuming b is of type Bla*
int i = c.doSomething(true);   // Assuming c is of type Bla

To call the non-static function we have two options:

string s = b->getName();       // Assuming b is of type Bla*
string s = c.getName();        // Assuming b is of type Bla