"santosh" <sa*************@in.bosch.com> wrote in message
news:de**********@ns2.fe.internet.bosch.com...
Hello,
I have a doubt about static variable.
class B
{
private:
static int x;
public:
static set(int y)
{
x=y;
}
};
int B::x=10;
class D1: class B
{
}
class D2: class B
{
}
Here if I modify the static variable by an object of class D1, then for
the
object of D2 the same modification is visible.
Here suppose I want that D2 object's x should not be modified by
modifying
D1 object's x.
How to acheive this?
Can it anyway be done by using templete class.
The one and only static variable you have here is B::x. It is the compiler
that translates D1::x, D2::x, (and o.x when o is an object of type B, D1 or
D2) into B::x. Therefore, they are all just one thing.
To achieve you goal, just declare and define a static x in both D1 and D2.
However, by this way, changing D1::x or D2::x will not have effect on B,
since now D1::x, D2::x and B::x are all different things.
If, however, you want to change the static x for the base class but have D1
and D2 each maintaining individual static objects, you need two bases, say
B1 and B2:
class B1{public: static int x;};
class B2{public: static int x;};
int B1::x = 0;
int B2::x = 0;
class D1: public B1{};
class D2: public B2{};
This of course can simply apply a template as you have been mentioning:
template <typename T>
class B{public: static int x;};
template <typename T>
int B<T>::x = 0;
class D1: public B<D1>{};
class D2: public B<D2>{};
Note that B<D1> and B<D2> are totally different types, so D1 and D2 does NOT
share a common base. To remedy, you can make a common base for all B<T>:
class CommonBase{};
template <typename T>
class B: public CommonBase
{public: static int x;};
template <typename T>
int B<T>::x = 0;
class D1: public B<D1>{};
class D2: public B<D2>{};
Ben