Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implicitly constructed variables in c++

Tags:

c++

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; ?

like image 699
Giswok Avatar asked Apr 17 '15 14:04

Giswok


Video Answer


2 Answers

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.

like image 109
Mike Seymour Avatar answered Sep 25 '22 13:09

Mike Seymour


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()() };
like image 42
bobah Avatar answered Sep 22 '22 13:09

bobah