Hey guys,

So I've been working on a program that takes a student id and name but however I got a weird error saying:
error: expected ‘(’ before ‘.’ token
error: expected ‘{’ before ‘.’ token
and it occurs around the name_first(firstName), name_.second(lastName). I'm having trouble to get the pairs working.

typedef std::pair<std::string, std::string> Name;

class Student {
public:
    explicit Student(const std::string& id, const std::string& firstName, const std::string& lastName)
        : id_(id), name_.first(firstName), name_.second(lastName){
            if(!isValidId(id) || !isValidName(name_)){
                throw "Student::Student(const string&, const string&, const string&): invalid input.";
            }


    }


private:
    std::string id_;
    Name name_;
}

Can anybody help me? Thanks.

delete line 6 and just make normal assignments inside he function. AFAIK you can only do what you did on line 6 with class reference variables, which id_ and name_ are not.

name_.first(firstName), name_.second(lastName)

C++ doesn't support initializing individual members of a member object in the initializer list. Ideally you'd want to add a constructor to the Name class that takes a first and last name, then write the initalizer list like this:

explicit Student(const std::string& id, const std::string& firstName, const std::string& lastName)
    : id_(id), name_(firstName, lastName){

    if(!isValidId(id) || !isValidName(name_)){
        throw "Student::Student(const string&, const string&, const string&): invalid input.";
    }
}

Otherwise, as Ancient Dragon mentioned, you'll need to eschew the initializer list and do a straight assignment in the constructor body:

explicit Student(const std::string& id, const std::string& firstName, const std::string& lastName)
    : id_(id){

    name_.first = firstName;
    name_.second = lastName;

    if(!isValidId(id) || !isValidName(name_)){
        throw "Student::Student(const string&, const string&, const string&): invalid input.";
    }
}

Ah I see now, thanks a lot.

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.