Docsity

Static Members - Advanced Programming - Lecture Slides, Slides of Computer Science

Partial preview of the text

Download Static Members - Advanced Programming - Lecture Slides and more Slides Computer Science in PDF only on Docsity!

Classes

Static Members

Static Members

  • Data and Functions Can be static
  • Exists Independently of Any Instantiated Objects

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

  • // client.cpp

#include “student.h”

main() {

student::print_instructor();

  • Output will be:

Notice that no instance of student is required.Instructor: Henry