Mr. Fourcan Karim Mazumder Faculty Dept. of Computer Science and Engineering
Mr. Fourcan Karim Mazumder Faculty Dept. of Computer Science and Engineering
private:
int m_nB; // private
int GetB() { return m_nB; } // private
protected:
int m_nC; // protected
int GetC() { return m_nC; } // protected
public:
int m_nD; // public
int GetD() { return m_nD; } // public
};
int main()
{
Access cAccess;
cAccess.m_nD = 5; // okay because m_nD is
public
cout << cAccess.GetD(); // okay because GetD() is
public
// cAccess.m_nA = 2; // WRONG because m_nA
is private
// cout << cAccess.GetB(); // WRONG because
GetB() is private
return 0;
}
Output:
5
Static member variables:
Static variables keep their values and are not
destroyed even after they go out of scope. For
example:
int GenerateID()
{
static int s_nID = 0;
return s_nID++;
}
int main()
{
std::cout << GenerateID() << std::endl;
std::cout << GenerateID() << std::endl;
std::cout << GenerateID() << std::endl;
return 0;
}
This program prints:
0
1
2
Note that s_nID has kept it’s value across multiple
function calls.
C++ introduces static member variables. Before we
go into the static keyword as applied to member
variables, first consider the following class:
class Something
{
private:
int m_nValue;
public:
Something() { m_nValue = 0; }
};
int main()
{
Something cFirst;
Something cSecond;
return 0;
}
When we instantiate a class object, each object
gets it’s own copy of all normal member variables.
In this case, because we have declared two
Something class objects, we end up with two
copies of m_nValue — one inside cFirst, and one
inside cSecond. cFirst->m_nValue is different than
cSecond->m_nValue.
Member variables of a class can be made static by
using the static keyword. Static member variables
only exist once in a program regardless of how
many class objects are defined! One way to think
about it is that all objects of a class share the static
variables. Consider the following program:
class Something
{
public:
static int s_nValue;
};
int Something::s_nValue = 1;
int main()
{
Something cFirst;
cFirst.s_nValue = 2;
Something cSecond;
std::cout << cSecond.s_nValue;
return 0; }
This program produces the following output:
2
Because s_nValue is a static member variable,
s_nValue is shared between all objects of the class.
Consequently, cFirst.s_nValue is the same as
cSecond.s_nValue. The above program shows that
the value we set using cFirst can be accessed using
cSecond!
Although you can access static members through
objects of the class type, this is somewhat
misleading. In fact, s_nValue exists even if there
are no objects of the class have been instantiated!