Presentation is loading. Please wait.

Presentation is loading. Please wait.

Classes Static Members

Similar presentations


Presentation on theme: "Classes Static Members"— Presentation transcript:

1 Classes Static Members
Department of Computer and Information Science, School of Science, IUPUI CSCI 240 Classes Static Members Dale Roberts, Lecturer Computer Science, IUPUI

2 Static Members Data and Functions Can be static
Exists Independently of Any Instantiated Objects

3 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

4 Static Data Members -- Example
// student.h #define size 20 class student{ char *name, *ss; static char *instructor; public: student(char *, char *); ~student(); };

5 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";

6 Static Data Members -- Example
// client.cpp #include “student.h” main() { student s1("John", " "); student s2("Tom", " "); s1.print(); s2.print(); } Name: John SS: Instructor: Henry Name: Tom SS: Instructor: Henry  

7 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()

8 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(); };

9 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";

10 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.

11 Acknowledgements These slides were originally prepared by Rajeev Raje, modified by Dale Roberts.


Download ppt "Classes Static Members"

Similar presentations


Ads by Google