Hi, I just started learning more about class/objects. What is the purpose of using 'this' pointers and static members? How exactly do you use them?

These are some small examples:

class SomeClass
  {
  private:
    int num;
  public:
    void setNum(int num)
    { this->num = num; }
};

What is 'this->' doing to num?

class IntVal
	{ 
    public:
	    intVal(int val = 0)
	    { value = val; valCount++ } 
	    int getVal();
	    void setVal(int);
	  private:
	    int value;       
	    static int valCount;
   };
   //In-class declaration    
      static int valCount;
      //Other members not shown
   };
   //Definition outside of class
   int IntVal::valCount = 0;

What is the purpose of making it static and setting it to 0?

The this pointer is used to refer to the current object being utilized. For instance, if you have an overloaded assignment operator for a class, and you'd like to test whether or not an object is being assigned to itself, that operator is used to check.

Based on your code, intVal, the i should be uppercase if that is your constructor. Aside from that, the purpose of valCount is to count how many objects you create of type IntVal. Static variables are allocated once and exist for the entirety of your program, and retains its value after being used.

Also, static variables are initialized to 0, for basic types, by default.

Edited 5 Years Ago by Chilton: n/a

Also, static variables are initialized to 0, for basic types, by default.

really? I thought you had to explicitly initialize them or else it would be a linkage error. So there is no default initialization.

Shouldn't you only need to explicitly initialize them when the value isn't going to be one?

Edited 5 Years Ago by Chilton: n/a

Static variables are allocated once and exist for the entirety of your program, and retains its value after being used.

Would you say its like a const value? Also I'm not really getting what the 'this' pointer is.

The reason that you are permitted to use the "this" pointer with a static data member, even though the pointer is ignored, is so that you can write a statement such as

p->v = 42;

without having to know whether v is static.

Otherwise, you would have to figure out the type of the object to which P points, and then write

P_type::v = 42;
This article has been dead for over six months. Start a new discussion instead.