C++ tutorial - static members


Static members

Each object created from a class has a copy of all its instance members. Values of instance data members and results of instance function members can vary from one object to another object. To access a public instance member, you must create an object from the class. There is an exception to this rule. In certain cases, a member of the class is shared to all objects. Its value or result does not vary from one object to another object. This kind of data member is call static member. For example, you might need a count data member of Student class to record the number of Student objects are instantiated. The count data member is shared to all objects of the Student class. Alternatively, you can say that all objects of the Student class share a single copy of the count data member. To define a static member, you need to use the static keyword. A static member can be private, protected, or public. You can access a public static member by writing the name of the class followed by the binary scope resolution operator (::). It also can by accessed through any object of the class. Generally, you can access private, and protected static member through public function members of the class. A static data member can only be initialized on once.

#include <cstdlib>
#include <iostream>

using namespace std;
class Student{

private: int id;
char *name;
char sex;
static int count; //static data member
public:
Student(int id,char *name,char sex){ //constructor
this->id=id;
this->name=name;
this->sex=sex;
count++;
}
~Student(){// destructor
count--;
}
void printInfo(){
cout<<id<<"\t"<<name<<"\t"<<sex<<endl;
}

//static function member
static int getCount(){return count;};

};

int Student::count=0; //initialize static data count  member

int main(int argc, char *argv[])
{

//create four objects
Student *st=new Student(101,"Dara",'m');
st->printInfo();
Student *st1=new Student(102,"Channa",'m');
st1->printInfo();
Student *st2=new Student(103,"Piseth",'m');
st2->printInfo();
Student *st3=new Student(104,"Panha",'f');
st3->printInfo();
cout<<"Number of objects instantiated:"<<Student::getCount()<<endl;
//selete one object
delete st;
cout<<"Number of objects after deleting one object:"<<Student::getCount()<<endl;
system("PAUSE");
return EXIT_SUCCESS;

}

static member


Comments




This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.