Classes Static Members Department of Computer and Information Science, School of Science, IUPUI CSCI 240 Classes Static Members Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui.edu
Static Members Data and Functions Can be static Exists Independently of Any Instantiated Objects
Static Data Members COMMON to All the Objects of that Class Exist Even When NO Class Objects Exist Definition for static Data Members is a Declaration in header file Initialization ONLY by an Initializer or an Assignment Statement inside a static member function Accessing -- class_name::data_name or object_name.data_name
Static Data Members -- Example // student.h #define size 20 class student{ char *name, *ss; static char *instructor; public: student(char *, char *); ~student(); };
Static Data Members – Example (cont) // student.cpp #include “student.h” #include <iostream> student::student(char *ip_name, char *ip_ss){ name = new char[size]; ss = new char[size]; strcpy(name, ip_name); strcpy(ss, ip_ss);} void student::print(){ cout << "Name: " << name << endl; cout << "SS: " << ss << endl; cout << "Instructor: " << instructor << endl;} }; /* Definition and Initialization of Static member */ char *student::instructor = "Henry";
Static Data Members -- Example // client.cpp #include “student.h” main() { student s1("John", "012345678"); student s2("Tom", "999999999"); s1.print(); s2.print(); } Name: John SS: 012345678 Instructor: Henry Name: Tom SS: 999999999 Instructor: Henry
Static Member Functions COMMON to All Objects of the Class Created by the Class Definition -- Exist Even when NO Class Objects Exist Can Only Access Static Data Members of the Class or other static member functions Accessing -- class_name::function_name() or object_name.function_name()
Static Member Functions -- Example // student.h #define size 20 class student{ char *name; char *ss; static char *instructor; public: student(char *ip_name, char *ip_ss); static void print_instructor(); };
Static Member Functions – Example (cont) // student.cpp #include “student.h” #include <iostream> student::student(char *ip_name, char *ip_ss){ name = new char[size]; ss = new char[size]; strcpy(name, ip_name); strcpy(ss, ip_ss);} static void student::print_instructor() { cout << "Instructor: " << instructor << endl;} /* Definition and Initialization of Static member */ char *student::instructor = "Henry";
Static Member Functions – Example (cont) // client.cpp #include “student.h” main() { student::print_instructor(); } Output will be: Instructor: Henry Notice that no instance of student is required.
Acknowledgements These slides were originally prepared by Rajeev Raje, modified by Dale Roberts.