Why should I use a closing bracket in this?

172 views Asked by At

I have some code which I could not compile it yet. The compiler says there should be a closing bracket, but I can't see a reason for this or place to put it. This is my code:

#include "Player.h"

Player(std::string val){
    set_Name(val);
    set_Alliance("NONE");
    set_LastUpdate();
}

Player(std::string val, std::string ally){
    set_Name(val);
    set_Alliance(ally);
    set_LastUpdate();
}

I have included in Player.h

This is the error:

error: expected ')' before 'val'

This is the prototype for constructor:

Player(std::string);

I am using GNU GCC compiler, under linux(ubuntu)

2

There are 2 answers

4
hyde On BEST ANSWER

You are missing the class name from constructor outside the class definition. Try this:

Player::Player(std::string val){  // constructor outside class definition
    set_Name(val);
    set_Alliance("NONE");
    set_LastUpdate();
}

Unverified speculation: With your current code, compiler sees Player(symbol1 symbol2) and takes that as creating object of class Player, and first thing it fails to understand is seeing two symbols as constructor argument, and gives a somewhat misleading error about that.

0
Andreas DM On

When you define methods, constructor, destructor etc. outside of the class, remember to tell the compiler that this belongs to the class using the class name following the scope operator :: and the name of the method, constructor, destructor etc with the matching parameters.

As a small example:

class Phone {
    string number;
public:
    string get_num();
    void set_num(string const &num) { number = num; }
};

// Pay attention to this:
// we tell the compiler that get_num belongs to class Phone
string Phone::get_num()
{
    return number;
}

int main()
{
    Phone p;
    p.set_num("123");
    cout << p.get_num() << endl;
}