Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

srand function in class [duplicate]

I am learning C++ and I can't seem to find an answer to my issue. When I run my code, I don't get any compiler errors, but I when I call a function "getVin()" (supposed to generate a random number with the use of "generate()" function) it doesn't do so. It outputs a zero. Here is my class (from header file):

class Vehicle {
public:
    Vehicle();
    static int generate();
    const int getVin () { return m_vin; }

protected:
    float m_lla[3];
    const int m_vin = s_idgen;

private:
    static int s_idgen;
};

And definition (from source file):

int Vehicle::s_idgen = generate();

Vehicle::Vehicle() {
    m_lla[3] = 0;
}

int Vehicle::generate() {
    srand((int)time(0));
    return (rand() % 10000) + 1;
}

Any advice would be helpful, thank you!

like image 622
LCKDWN Avatar asked Aug 12 '26 11:08

LCKDWN


1 Answers

I could partially reproduce, so I assume that you were bitten by the static initialization fiasco. I have just added:

Vehicle sveh; // static scoped

immediately after Vehicle declaration and before any method or static field definition, and then

int main() {
    Vehicle veh;
    std::cout << veh.getVin() << std::endl;
    std::cout << sveh.getVin() << std::endl;
    return 0;
}

Output is:

1915
0

That means that an automatic Vehicle correctly uses the random value (random for a run, but common to all instances...), while the static one was initialized before the static field initialization.

like image 88
Serge Ballesta Avatar answered Aug 15 '26 01:08

Serge Ballesta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!