| re: Some questions about static member
Tran Tuan Anh wrote:
[color=blue]
> Dear all,
>
> I am new with C++ and very confused with some features.
> Really appreciate if you can explain to me some of stuffs below.
>
> I define a class:
>
> class A {
> static A* instance = 0;
> };
>
> then I have error saying that I cannot initialize a static member
> inside the class. Why? As a newbie to C++ I don't see why not?[/color]
Because that's how C++ is defined.
[color=blue]
> then I move the initialization outside to A.cpp:
>
> A::instance = 0;[/color]
That wouldn't be an initialization. It would be an assignment, and
assignments are not allowed outside of a function.
The difference between initialization and assignment is that the former
creates a new object and gives it the specified value, whereas an
assignment just gives a new value to an already existing object.
[color=blue]
> then compiler complains and I have to do the following:
>
> A* A::instance = 0;
>
> Here I also don't see why.[/color]
Because in the class definition, you only declare 'instance', i.e. you say
that the class has a member with that name. But it isn't yet definied, i.e.
there is no storage for that object. Therefore, you have to add to one
translation unit a definition of that static member variable.
[color=blue]
> For example, if I have an interger:
>
> int i;
>
> then I initialize it by:
>
> i = 0;[/color]
Again, that's not an initialization, but an assignment. You can tell the
difference by the following rule:
type name = value; <- Initialization
name = value; <- Assignment
[color=blue]
> that is it. Why the instance var above need the A* type declearation.[/color]
It's unclear to me what you mean.
[color=blue]
> Basically, as a newbie to C++ I am very confused with huge syntaxs and
> semantics. Really want to learn more.[/color]
I hope I could help a bit. |