OOP - Week 4, Lecture 2: Static Members
Giving Every Student a Unique Id
Every student at the university has a different university id. If the constructor takes the id as a parameter, nothing stops the caller from giving two students the same one:
Student a(1001, 3.2);
Student b(1001, 3.9); // the same id twice
It is better when the class gives the ids, one after the other: 1001, 1002, 1003, and so on. To do that, the class has to remember the next id to give out. A normal data member cannot do this, because every object has its own copy, and a new student would start again from its own copy.
We need one variable that belongs to the class itself, and that all the objects share. This is a static member. In this lecture we use static on data members and on member functions.
1. Static Data Members
A static data member is a variable that is shared by all objects of the class. There is only one copy of it, no matter how many objects exist. Write static before the declaration:
class Student {
private:
const int id;
double gpa;
static int nextId; // one copy, shared by all students
};
id and gpa exist inside each object, so every student has its own. nextId does not exist inside the objects. It exists once, and every student uses the same one.
A static data member is only declared inside the class. It must also be defined once, outside the class, with the class name and ::. This is where it gets its starting value:
int Student::nextId = 1001; // defined once, outside the class
The starting value is your choice. It decides which ids the students get:
int Student::nextId = 0; // the ids are 0, 1, 2, 3, ...
int Student::nextId = 20260001; // the ids are 20260001, 20260002, 20260003, ...
Do not write
staticagain in the definition. If you forget the definition, the program does not link, and the linker (the tool that joins the compiled files into one program) reports an undefined reference toStudent::nextId.
When the class is split into files, the definition goes in Student.cpp, not in Student.h. If it were in the header, every file that includes the header would define it again, and the linker would report that it is defined more than once.
The constructor uses it to give the id. The id is a const data member from Lecture 1, so it is set in the member initializer list:
class Student {
public:
Student(double g) : id(nextId++), gpa(g) {
}
};
nextId++ gives the current value to id, and then adds 1 to nextId. The first student gets 1001 and nextId becomes 1002. The second student gets 1002, and so on.
Destroying a student does not change
nextId. If the student with id 1003 is destroyed, the next student still gets the next number, not 1003. The constructors never give the same id twice.
A static data member can be private, like any other. The functions of the class can use it directly, and the rest of the program needs a function to read it.
2. Static Member Functions
A static member function belongs to the class, not to an object. Write static before the function:
class Student {
public:
static int getNextId() {
return nextId;
}
};
You call it with the class name and ::. No object is needed, so you can call it even when no student exists:
cout << Student::getNextId(); // works with zero students
You can also call it on an object, as in a.getNextId(), and it does the same thing. The class name is clearer, because it shows that the function does not depend on a. A static function can be called through a const object too, because it never touches the object.
A static function is not called on an object, so it has no object to work with:
- It can use static data members and other static functions.
- It cannot use a non-static member by its name only, such as
idorprint(). By its name only, the compiler does not know which object it belongs to. - It cannot be a const member function (Lecture 1), because a const function promises not to change the object it is called on, and a static function has no object.
class Student {
private:
const int id;
static int nextId;
public:
static int getId() {
return id; // error: invalid use of non-static data member 'id'
}
static int getNextId() {
return nextId; // works: nextId is static
}
};
The reverse is allowed: a normal member function can use static members freely, because it always has an object. The constructor above used nextId for this reason.
Compare print(), a normal function, with getNextId(), a static function:
| ย | print() (normal) | getNextId() (static) |
|---|---|---|
| How you call it | a.print(); | Student::getNextId(); |
| Does the function have an object to work on? | yes | no |
Can the function use id by its name only (not static)? | yes | no |
Can the function use nextId (static)? | yes | yes |
Can the function be marked const? | yes | no |
A few facts about static data members:
- They do not make the objects bigger, because they are not stored inside the objects.
- They exist even when no object has been created.
nextIdalready holds 1001 before the first student. - A change made through one object is seen by all the others, because it is the same variable.
3. Counting the Objects and Copies
A static data member can also count the objects. Add a second one, count, defined like nextId with int Student::count = 0;. The constructor adds 1, the destructor subtracts 1, so count always holds the number of students that exist right now. This time the number does go down when a student is destroyed:
class Student {
private:
const int id;
double gpa;
static int nextId;
static int count;
public:
Student(double g) : id(nextId++), gpa(g) {
count++;
}
~Student() {
count--;
}
static int getCount() {
return count;
}
};
A copy is a new student too, so it needs a new id and it must be counted. The copy constructor that the compiler writes does neither: it copies the id, so two students would have the same id, and it does not change count. So we write the copy constructor ourselves (Lecture 3 of Week 2):
Student(const Student& other) : id(nextId++), gpa(other.gpa) {
count++;
}
4. Putting It Together
This program gives the ids, and it is split into three files as in Week 3. nextId is declared in Student.h and defined in Student.cpp, with the value 1001. The constructor takes the next id, and Student::getNextId() reads the number that will be given next. A student in a block is destroyed, and the next student still gets a new id.
#ifndef STUDENT_H
#define STUDENT_H
class Student {
private:
const int id; // set once, never changes
double gpa;
static int nextId; // declared here: one copy, shared by all students
public:
Student(double g);
int getId() const;
void print() const;
static int getNextId(); // a static function: no object needed
};
#endif#include <iostream>
#include "Student.h"
using namespace std;
int Student::nextId = 1001; // defined once, here in the .cpp file
Student::Student(double g) : id(nextId++), gpa(g) { // take the next id, then move it forward
}
int Student::getId() const {
return id;
}
void Student::print() const {
cout << "id " << id << ": gpa " << gpa << endl;
}
int Student::getNextId() { // no "static" here, only in the class
return nextId;
}#include <iostream>
#include "Student.h"
using namespace std;
int main() {
cout << "next id: " << Student::getNextId() << endl; // before any student
Student a(3.2);
Student b(3.9);
a.print();
b.print();
{
Student c(2.8);
c.print();
} // c is destroyed here
Student d(3.5);
d.print(); // not 1003: ids are not reused
cout << "next id: " << Student::getNextId() << endl; // after four students
return 0;
}Click each line of output to see what caused it.