Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static members and the default constructor C++

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?

like image 742
rubixibuc Avatar asked Sep 09 '11 23:09

rubixibuc


People also ask

What are the properties of a static 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.

When is a static constructor called in Java?

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.

What is default constructor in C++?

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.

What is a static member in C++?

"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.


1 Answers

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.

like image 111
Kerrek SB Avatar answered Nov 07 '22 22:11

Kerrek SB