I came across a statement in my book that said:
You don't have to initialize a static member when you declare it; C++ will invoke the default constructor if you don't.
This really has me confused as to what it means. Are they talking about object members only? If so, at what point would it call the default constructor? Also, how would you initialize a static member object without the default constructor?
A static constructor does not take access modifiers or have parameters. A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.
A static constructor is called automatically. It initializes the class before the first instance is created or any static members are referenced. A static constructor runs before an instance constructor. A type's static constructor is called when a static method assigned to an event or a delegate is invoked and not when it is assigned.
Default Constructor A default constructor is parameterless. If a class doesn't have a constructor then a default constructor gets called when object is created. The default constructor is added to a class by default if you don't add any constructor to your class. The default constructor should have public access.
"The static member" means the "static member" of some primitive types member variable, in another word, the data types of the "static member" should only be: int, float, or char..... So for these primitive types, compiler know their "default constructor", e.g. for the "int" type, compiler just set 0.
Let's break it down. Suppose there's some class Foo;
somewhere. Now we make this a static member of our class,
class Star
{
static Foo z;
// ...
};
Now in essence that declares a global object Foo Star::z
-- so how does this get instantiated? The standard tells you: it gets default-constructed. But remember that you have to provide the actual object instance in one of your translation units:
// in, say, star.cpp
Foo Star::z; // OK, object lives here now
Now suppose that Foo
doesn't actually have a default constructor:
class Foo
{
public:
Foo(char, double); // the only constructor
// ...
};
Now there's a problem: How do we construct Star::z
? The answer is "just like above", but now we have to call a specific constructor:
// again in star.cpp
Foo Star::z('a', 1.5);
The standard actually has two distinct notions of "initialization" (a grammatical concept) and "construction" (a function call), but I don't think we need to go into this just now.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With