0

I've just started looking at C++ and I am having some problems I can't wrap my head around.

I am trying to do something as simple as creating a class with a function, call that function and read the returned value.

However I am stuck at what I guess is a minor issue.

I know that it is the call from main to Die -> randomNumber that causes this error but I dont know why. I even tried to return the number 12 from the function without any luck.

Error: error

I have 3 files (main.cpp, Die.h and Die.cpp)

main.cpp

#include <string>

#include "Die.h"

using namespace std;

int main() {
    Die * test = new Die();

    cout << std::to_string(test->randomNumber(4)) << endl;

    return 0;
}

Die.h

#pragma once

#include <iostream>
#include <ctime>
#include <cstdlib>

class Die
{
public:
    Die();
    ~Die();
    void init();
    void rollDie(int&, int&);
    void rollDie(int*, int*);
    int randomNumber(int);

};

Die.cpp

#include "Die.h"

Die::Die()
{
}


Die::~Die()
{
}

void Die::init() {

}

int randomNumber(int max) {
    srand(static_cast<unsigned int>(time(0)));
    return (rand() % max + 1);
}

void rollDie(int& die1, int& die2) {

}

void rollDie(int* die1, int* die2) {

}
Andrew Larsen
  • 1,257
  • 10
  • 21
  • 2
    As an aside: Don't call `srand()` in `randomNumber` -- call it once, in `main()`. As written, you'll get the same random number every time you roll a die during one second, because you're reseeding the RNG for every call. –  Jan 23 '17 at 20:31
  • Noted, thanks will move srand to main :) – Andrew Larsen Jan 23 '17 at 20:32
  • Relevant answer of the duplicate: [What is an undefined reference/unresolved external symbol error and how do I fix it?](http://stackoverflow.com/a/12574407/962089). It's the section with the big heading saying that a common error is forgetting to qualify the name. – chris Jan 23 '17 at 20:37
  • I did search before asking this question, I rarely ask any questions here. But I couldn't find a solution to the problem. But yes I could have done more searching before asking. – Andrew Larsen Jan 23 '17 at 20:40

2 Answers2

4

You're missing the class specifier on the declaration of randomNumber and rollDie.

int Die::randomNumber(int max)

Without those you're just declaring a global function named randomNumber, but the linker is attempting to choose Die::randomNumber which it cannot find.

lcs
  • 4,227
  • 17
  • 36
2

In Die.cpp, you need to prefix member functions with the class name:

int Die::randomNumber(int max) { ... }

void Die::rollDie(int& die1, int& die2) { ... }

void Die::rollDie(int* die1, int* die2) { ... }

Without that, the compiler thinks you're just defining global functions. It has no reason to suspect they should be members to a class if you don't tell it.

qxz
  • 3,814
  • 1
  • 14
  • 29