STATIC DATA MEMBERS & CONSTANT MEMBER FUNCTIONS
Static data members
static data member is a data member that is shared by all the objects of a class.Only one copy of static data member is kept in memory
By this example your idea will be clear about static data members
static data members
#include <iostream>
using namespace std;
class alpha
{
private:
int id;
static int count;
public:
alpha()
{
count++;
id=count;
}
void print()
{
cout<<"My id is"<<id;
cout<<"count is"<<count;
}
};
int alpha ::count=0; //definition of count
void main ()
{
alpha a1,a2,a3;
a1.print();
a2.print();
a3.print();
}
This example will clear your idea . This simple ,easy and awesome space for beginners
....................................................................................................................................................................................
Constant data members
If you dont want to change data members then keyword const is used.
This example demonstrates const member functions
class aclass
{
private:
int alpha;
public:
void nonFunc() // non const member function
{
alpha=100; //ok
}
void conFunc() const // constant member function
{
alpha=100; // error , cannot modify a member
}
};
This example surely help you in understanding of const member function
This is a completely solved example.
#include <iostream>
using namespace std;
class rational
{
private:
int num;
int dnum;
public:
rational():num(1),dnum(1)
{}
void get ()
{
cout<<"enter numerator";
cin>>num;
cout<<"enter denomenator";
cin>>dnum;
}
void print () const // const keyword is used
{
cout<<num<<"/"<<dnum<<endl;
}
void multi(rational r1,rational r2)
{
num=r1.num*r2.num;
dnum=r1.dnum*r2.dnum;
}
};
void main ()
{
rational r1,r2,r3;
r1.get();
r2.get();
r3.multi(r1,r2);
r3.print();
}
For practice you should solve one more programming example like distance class. Practice makes a man perfect