I'm getting to grips with c++ and there's one language feature I'm having particular trouble getting my head around.
I'm used to declaring and initialising a variable explicitly, but in c++ we sometimes seem to declare and implicitly construct a variable.
For example in this snippet rdev seems to be implicitly constructed (as it is subsequently used to construct a default_random_engine);
random_device rdev;
default_random_engine gen(rdev());
Can someone explain what's going on here? How can I tell this apart from a simple declaration such as int myInt; ?
Can someone explain what's going on here?
These are definitions, not just declarations. A variable definition creates the variable. In the first case, there's no initialiser, indicating that it should be default-initialised.
How can I tell this apart from a simple declaration such as
int myInt;?
That's also a definition, creating the int variable and leaving it uninitialised.
You can declare a global variable without defining it:
extern int myInt;
extern indicates that it has external linkage, and is defined somewhere else. Other kinds of variable can't be declared without defining them.
random_device rdev; // creates an instance of random_device on the stack
                    // with default constructor (taking no arguments)
default_random_engine gen(  // creates an instance of default_random_engine
                            // on the stack
    rdev()                  // passing it the result of
                            // invocation of operator '()'
                            // on the instance rdev of random_device
);
Same in a more verbose form (with some C++11):
auto rdev = random_device {};
auto gen = default_random_engine { rdev.operator()() };
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