Docsity

Static Data Member - Object Oriented Programming - Lecture Slides, Slides of Object Oriented Programming

Partial preview of the text

Download Static Data Member - Object Oriented Programming - Lecture Slides and more Slides Object Oriented Programming in PDF only on Docsity!

Object Oriented Programming (OOP) Lecture No. 12

Review

  • Constant data members
  • Constant objects
  • Static data members

Static Data Member

  • They are shared by all instances of the class
  • They do not belong to any particular instance of a class

Class vs. Instance

Variable

  • Student s 1 , s2 , s3 ;

Class Space

s1 (rollNo,…)

s2 (rollNo,…)

s3 (rollNo,…)

Class^ Instance Variable Variable

Defining Static Data Member

  • Static data member is declared inside the class
  • But they are defined outside the class

Defining Static Data Member class ClassName{ … static DataType VariableName; };

DataType ClassName::VariableName;

Example

class Student{ private: static int noOfStudents; public: … }; int Student::noOfStudents = 0; /private static member cannot beaccessed outside the class except for initialization/

Initializing Static Data

Member

  • If static data members are not explicitly initialized at the time of definition then they are initialized to 0

Accessing Static Data

Member

  • To access a static data member there are two ways - Access like a normal data member - Access using a scope resolution operator ‘::’

Example

class Student{ public: static int noOfStudents; }; int Student::noOfStudents; int main(){ Student aStudent; aStudent.noOfStudents = 1; Student::noOfStudents = 1; }

Example

class Student{ public: static int noOfStudents; }; int Student::noOfStudents; int main(){ Student::noOfStudents = 1; }

Example

class public: Student{

};^ static int noOfStudents; int Student::noOfStudents; int main(){ { Student aStudent; }^ aStudent.noOfStudents = 1; }^ Student::noOfStudents = 1;

Example

  • Modify the class Student such that one can know the number of student created in a system

Example

class Student{ … public: static int noOfStudents; Student(); ~Student(); … }; int Student::noOfStudents = 0;