Hello guys,

This class creates aDie object by using aRandomNumberGenerator and the concept of composition. The program works if the member object aRandomNumberGenerator is not declared static. Otherwise I receive the error "undefined reference to aDie::gen." I do not understand why this happens, isn't gen within the class scope? Even if I declared it static
other member functions should access it without any issues, or at least that's what i believe.

Thanks in advance for the help!

#ifndef DIE_H
#define DIE_H

#include "aRandomNumberGenerator.h"

class aDie
{
    public:
        aDie();
        double roll(); 
        void seed (int s);
        int inputSeed();
        ~aDie();
        
    private:
        static aRandomNumberGenerator gen;
};

#endif


#include <iostream>
#include "aDie.h"
#include <cmath>
using namespace std;

aDie::aDie()
{
   
}

double aDie::roll()
{   
    return (fmod(gen.generate(), 6) + 1);
}

void aDie::seed(int s)
{
    gen.setSeed(s);
}

int aDie::inputSeed()
{
    int value;
    
    cout << "Please enter a seed value: ";
    cin >> value;
    
    seed(value);
    
    return value;
}

aDie::~aDie()
{
    //Destructor does nothing in this case.
}

Recommended Answers

All 3 Replies

A static member does not belong to the object(this), rather, belongs to the class. The following code should make it more clear:

class foo
{
  public:
     static int foo1;  //Static member
     int foo2;         //Regular member
};

int main(int argc, char *argv[])
{
  foo Obj;
  Obj.foo2  = 2;  //Correct 
  Obj.foo1  = 1;  //Incorrect, foo2 does *not* belong to the object
  foo::foo1 = 1; //Correct, foo2 belongs to the class.
}

You need to declare the static member outside of the class definition like so

#ifndef DIE_H
#define DIE_H

#include "aRandomNumberGenerator.h"

class aDie
{
    public:
        aDie();
        double roll(); 
        void seed (int s);
        int inputSeed();
        ~aDie();
        
    private:
        static aRandomNumberGenerator gen;
};

#endif


#include <iostream>
#include "aDie.h"
#include <cmath>
using namespace std;

aRandomNumberGenerator aDie::gen;
// or
// aRandomNumberGenerator aDie::gen( ... );
// or
// aRandomNumberGenerator aDie::gen = new aRandomNumberGenerator( ... );


aDie::aDie()
{
   
}

double aDie::roll()
{   
    return (fmod(gen.generate(), 6) + 1);
}

void aDie::seed(int s)
{
    gen.setSeed(s);
}

int aDie::inputSeed()
{
    int value;
    
    cout << "Please enter a seed value: ";
    cin >> value;
    
    seed(value);
    
    return value;
}

aDie::~aDie()
{
    //Destructor does nothing in this case.
}

Thanks for the help guys!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.