When will I make any class member static

There are only two types of members inside a class

  1. Data
  2. Functions

When an object of a class is created data members are allocated memory space. For example if you will create 10 different objects of a class then there will be 10 copies of data members in the memory. Each object has its own copy of data members. But functions are just allocated memory space only once. No matter how many objects you create for a class, the functions will only get memory once.

The biggest motivation for making a class member static is to have just a single copy of that member in memory. For example if you make a data member of a class static then it will only have a single copy in memory. As discussed in the previous tutorial static members are not dependent of objects. So no matter how many objects you create for your class the static data members will just get memory once. Therefore when you want just a single copy of your data member in memory you should make it static.

Functions on the other hand just get memory space once and are not dependent on the object creation for memory allocation. Therefore the only motivation you can have for making a function static is ease of use. In the next tutorial we will discuss how to access the static members of a class. There you will understand that if you make a function static you can access it directly by using the class name and do not have to create an object to access it.

Making the whole class static

If you want all the members in a class, including data and functions, to be static then you can mark the class as static. This will force all the members to be marked as static.

static class Test  {  }

In the above class you will have to mark all the members as static or else you will get compile time error.

Quick Links

E-Magazines

@

Total Followers
Study Group Created
Study Group Joined
Following Teacher
Following Organization
Blog Articles Added
Questions Asked
Questions Answered
Jobs Posted
Total Members in Group
Questions asked by members
Tasks added in this Group

Please wait..

Ok

Login to Open ESchool OR Create your account    Login   SignUp