Question

I am just learning C++. I already know C and Java. Could someone please show me how to create a static method/function in C++ like I would in Java. For example, just for practice I am writing a Student class with the standard information (name, student number, gpa, etc). I want to make a static method/function that would return the total number of student objects created. I know in Java it would be:

public static int getNumStudents () {
    return totalStudentsCreated; // global variable
}

Thank you. :)

Était-ce utile?

La solution

Here is how in C++

class Student {
   private:
      static int totalStudentsCreated;
   public:
      static int getNumStudents();
};

int Student::totalStudentsCreated = 0;

int Student::getNumStudents() { return totalStudentsCreated; }

Should be covered in your C++ text book

Autres conseils

Static method

You need to put the method inside the Student class and mark it static. You need to remember in the future that unfortunately C++ does not allow const static methods at this point of time, however. You will also only be able to manipulate "global", "file-scope static", or "static member data" variables.

That is petty much all about it. You could write this:

class MyClass {
   public:
      static int getNumStudents() { return totalStudentsCreated; }
};

Then you would call the method this way:

int numStudents = MyClass::getNumStudents();

or

int numStudents = myClass.getNumStudents();

Although, this latter may not work with all the compilers out there, so try to stick to the former variant.

Static function (without Class)

If you only need a static function without an external class, then you could write the following:

static int getNumStudents() { return totalStudentsCreated; }

and then use it as follows:

int numStudents = getNumStudents();
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top