Kenny
Kenny

Reputation: 365

passing string by reference wrong c++

I am writing a simple class and get some error. The header file is shown below:

//
//  temp.h
//

#ifndef _TEMP_h
#define _TEMP_h

#include <string>
using namespace std;

class GameEntry {
public:
  GameEntry(const string &n="", int s=0);
  string getName();
  int getScore();
private:
  string name;
  int score;
};

#endif

And the method file is shown below:

// temp.cpp

#include "temp.h"
#include <string>
using namespace std;

GameEntry::GameEntry(const string &n, int s):name(n),score(s) {}

string GameEntry::getName() { return name; }

int GameEntry::getScore() { return score; }

The main file is shown below:

#include <iostream>
#include <string>
#include "temp.h"
using namespace std;

int main() {
  string str1 = "Kenny";
  int k = 10;
  GameEntry G1(str1,k);

  return 0;
}

I got error like this:

Undefined symbols for architecture x86_64:
  "GameEntry::GameEntry(std::__1::basic_string<char, std::__1::char_traits<char>,
                        std::__1::allocator<char> > const&, int)", referenced from:
      _main in main1-272965.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Can anyone tell me what's wrong? Many thanks.

Upvotes: 1

Views: 286

Answers (3)

clcto
clcto

Reputation: 9648

You cannot put the default parameters in the definition:

GameEntry::GameEntry(const string &n, int s):name(n),score(s) {}

Edit: Actually you can put it in the definition, but you cannot put it in both the definition and declaration. More information can be found in this question: Where to put default parameter value in C++?

Upvotes: 2

joelmeans
joelmeans

Reputation: 122

In addition to correcting the issues with default parameters, as pointed out by clcto and G. Samaras, you will need to compile temp.cpp to an object file (temp.o) and link it with main.cpp. Try this:

g++ -c temp.cpp

g++ main.cpp temp.o.

The symbols that are missing are found in the object file, which you aren't creating if you don't explicitly compile temp.cpp. I think you are probably misremembering what has worked in the past.

Upvotes: 1

gsamaras
gsamaras

Reputation: 73366

You can't have defaults values both in the .h and .cpp files.

Change the prototype in the header file to this:

GameEntry(const string &n, int s);

and you good to go.

In main.cpp, you missed a semicolon here: int k = 10


An interesting link: Where to put default parameter value in C++?

Long story short, it's up to you.

If it is in the header file, it helps documentation, if it is in the source the file it actually helps the reader who reads the code and doesn't just use it.

Upvotes: 1

Related Questions