in a class. I declare it in header and define/intialize it in the cpp file,
normally.
If I declare it as a global variable in my project, will that be initialized
at the point of declaraion?
thanks
Yes, globals are initialized before main or WinMain are called.
--
Scott McPhillips [VC++ MVP]
Chris:
What do you mean by "local variable in a class"?
Non-static (instance) member variable?
or
Static member variable?
Instance member variables are initialized with the object instance.
Static member variables are much like globals. As Scott says, they are
initialized before main() is entered.
--
David Wilkinson
Visual C++ MVP
another question:
class B;
class A
{
public:
vector<B> v;
B b;
A(){}
};
will v and b be initialized in the above class? If not, how should I?
Thanks
Chris
"Scott McPhillips [MVP]" wrote:
> .
>
"David Wilkinson" wrote:
> .
>
Your code will not compile as given because class B is not defined (and for
other reasons).
But if the code were complete, the answer is that b and v will be initialized
for each A object that you create, but not otherwise.
class A
{
public:
int i;
vector<B> v;
B b;
A(){}
};
If I do not initialize i, as
int A::i = 0;
I think i is not initialized and there could be anyting in i, when I do "A
a;".
So why can a class type as v and B be initialized?
"David Wilkinson" wrote:
> .
>
Classes have constructors, which are called when they are instantiated. For
example, vector is initialized to an empty state by its constructor when it
is created.
But integers and other "plain old data" types are not classes and do not
have constructors in C++. So yes, there could be anything in i.
This can only be done for static members (try it - you'll get a compiler error). Non-static members should be initialized in the constructor, as in
A::A() : i(0) {}
> I think i is not initialized and there could be anyting in i, when I do "A
> a;".
> So why can a class type as v and B be initialized?
Because B and vector are classes and have their own constructors. Default constructors for b and v are automatically invoked as part of A's constructor. On the other hand, plain ints don't have constructors, and so need to be initialized explicitly.
If your C++ textbook doesn't explain this, I strongly suggest you get a better one. This is really basic stuff.
--
With best wishes,
Igor Tandetnik
With sufficient thrust, pigs fly just fine. However, this is not necessarily a good idea. It is hard to be sure where they are going to land, and it could be dangerous sitting under them as they fly overhead. -- RFC 1925
"Igor Tandetnik" wrote:
> .
>