Home > OS >  Passing class as a parameter c
Passing class as a parameter c

Time:08-03

im new to programming and just start learning C a few weeks, im current doing the random number stuff, but i don't understand why the parameters sometime has "()" and sometime doesn't, hope someone can explain to me, thanks!.

int main()
{
    random_device rd;
    mt19937 rdn(rd()); //Why this parameter needs "()"?
    uniform_int_distribution<int> maxrd(1, 5000);
    
    int n = maxrd(rdn); //And why this parameter doesn't need "()"?

    cout << n;
};

CodePudding user response:

Case 1

mt19937 rdn(rd());

In the above statement, rd() uses(calls) the overloaded std::random_device::operator() and then the return value from that is used as an argument to mt19937's constructor.

Basically the parenthesis () is used to call the operator() of std::random_device. That is, here the parenthesis () after the rd are there because we want to pass the returned value from rd() as argument and not rd itself.

Case 2

int n = maxrd(rdn);

In the above statement, we're calling std::uniform_int_distribution::operator() which takes a Generator as argument and so we're passing rdn as an argument since rdn is already a generator.

Note here we're not using () after rdn because we want to pass rdn as argument and not the returned value from rdn().

  •  Tags:  
  • c
  • Related