This is a simple, one-file example of a UML class diagram and the corresponding C++ class. The constructors initialize the member variables, and the display function prints the current member variable values to the console.
The student UML class diagram.
The UML is a visual language consisting of multiple diagrams, each with an established syntax, that describes various aspects of software systems. Class diagrams capture a program's static architecture, consisting of its classes and their interconnections. Some UML diagramming tools selectively hide or display class detail, allowing users to choose how much information to display at any given time. The example includes all three sections of the student UML diagram.
#include <iostream>
#include <string>
using namespace std;
class student
{
private:
string name = ""; // (a)
int wnum = 0;
public:
student() {} // (b)
student(string n, int i) // (c)
{
name = n;
wnum = i;
}
//student(string n, int i) : name(n), wnum(i) {} // (c - preferred)
void display() // (d)
{
cout << name << ", " << wnum << endl;
}
};
int main()
{
student sb_pres("Alice", 123); // (e)
sb_pres.display(); // (f)
student class_pres("Dilbert", 987); // (e)
class_pres.display(); // (f)
return 0;
}
The student class example.
The student class demonstrates the basic elements of a C++ class and a few helpful options. It implements the constructors and display function inline, which is appropriate for small functions.
Matching the UML diagram, the example makes the member functions private. The highlighted default initializers are optional, but when used, they typically initialize an object to an "empty" or default state. The meaning of "empty" depends on each member's type and the class's purpose.
Although the default constructor doesn't perform any operations, it is necessary to utilize the default initializers.
The parameterized constructor initializes the member variables with values provided by the client, the main function in this example. The first version is easy to understand. The second version is preferred because the initializer list runs before the constructor's body, initializing the member variables before statements in the body can use them. In this example, the constructor only initializes the member variables, so the body is empty.
The display demonstrates the basic member function syntax.
The statements instantiate two student objects, calling a constructor and passing a name and ID number as arguments.
The statements demonstrate the member function calling syntax that temporarily binds the display function to different objects through the this pointer. The text revisits the this pointer in detail in a few sections.