9.7. student Class Example
This is a simple, one-file example of a UML class diagram and the corresponding C++ class. The constructor initializes 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 language with an established syntax. We can choose how much information we want to display. We'll include all three sections in the student UML diagram. We put the name in the top section, the attributes in the middle section, and the operations in the bottom section. The "-" symbol denotes private
features while the "+" symbol denotes public
features.
#include <iostream>
#include <string>
using namespace std;
class student
{
private:
string name;
int wnum;
public:
student(string n, int i)
{
name = n;
wnum = i;
}
void display()
{
cout << name << ", " << wnum << endl;
}
};
int main()
{
student sb_pres("Alice", 123);
sb_pres.display();
student class_pres("Dilbert", 987);
class_pres.display();
return 0;
}
The student example .
The constructor and the display function are typical examples of inline functions.
The statements student sb_pres("Alice", 123); and student class_pres("Dilbert", 987); instantiate two student objects: sb_pres and class_pres respectively. Both statements also call the student constructor function: student(string n, int i) . Both function calls have a string as their first argument and an int as their second, which matches the parameters in the function prototype.
The statements sb_pres.display(); and class_pres.display(); temporarily bind the display function to two different objects: first to sb_pres and then to class_press . During the respective function calls, display() is bound to each object through the this
pointer.
Back |
Chapter TOC |
Next