Docsity

Understanding Static Data Members in Object-Oriented Programming, Slides of Object Oriented Programming

Partial preview of the text

Download Understanding Static Data Members in Object-Oriented Programming 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 allinstances of the class ►They do not belong to anyparticular instance of a class

Class vs. Instance Variable

►Student

s

s

,^

s

Class Space

s1 (rollNo,…)

s2 (rollNo,…)

Instance Variable s3 (rollNo,…)

ClassVariable

Defining Static Data Member

►Static data member is declared inside theclass ►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

/*private

static

member

cannot

be accessed

outside

the

class

except

for

initialization*/

  • Initializing Static Data Member ►If static data members are notexplicitly initialized at the timeof definition then they areinitialized to

Accessing Static Data Member ►To access a static data member there aretwo 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 Student{public: static int noOfStudents; };int Student::noOfStudents;int main(){ { Student aStudent;aStudent.noOfStudents = 1;} Student::noOfStudents = 1; }

Example

►Modify the class Student suchthat one can know the numberof student created in a system

Example

class

Student{ … public:static

int

noOfStudents;

Student();~Student();… };int^ Student::noOfStudents

=^