Reputation: 2973
#include "B.h"
class A
{
public :
A()
{
s_b = new B();
b = new B();
}
static B *s_b;
B *b;
};
#include<iostream>
using namespace std;
#include "A.h"
int main()
{
cout<<"hello";
}
In my project I have seen static object as above. But not able to know what is the exact use of it and how they are different from general object. Please help me in finding out what I can do with s_b which is not being done by b.
Upvotes: 0
Views: 102
Reputation: 11047
generally speaking static members have to be initialized outside the declaration of the class except for constant int type if you are not using C++11.
So your code posted above is flawed. you need a statement like
A::s_b = B();
outside the class A { ... }; To initialize an static member inside an non static constructor is wrong because the constructor is used to construct an object but the static member does not belong to the object but belong to the class. So these static members can not be modified through static member functions.
Think "class" as "human being" and an object of that "class" as a specific person, like "John Smith". So if you have a field, "salary". That should be a non-static field since each person has a different salary. But if you have field, "total_population", which should be a static member because this field semantically does not belong to one specific person but to the whole "human being".
Upvotes: 1
Reputation: 153909
The only real difference between a static member and an object or function defined at namespace scope is access. A static data member can be private, for example, in which case it cannot be accessed outside of the class; and a static function member can access private data members, which a function at namespace scope cannot.
The access syntax is also different: if outside the class, you must use ClassName::memberName
(or classInstance.memberName
) to access the member. There is no using
which can make it accessable otherwise.
Upvotes: 2
Reputation: 258568
For one, s_b
doesn't take up memory for each instance of A
that is created, whereas b
does. The sizeof(A)
is increased by b
, but not by s_b
.
A static
is shared between all instances of the class, so it acts like a global. You don't need an object to access it, you can use A::s_b
directly.
Upvotes: 3