Search code examples
c++oopencapsulationaccessor

C++ class attribute undefined for non-accessor methods


I can't figure out why the following (greatly simplified) code returns the error error: 'm_sID' was not called in this scope:

#include <iostream>
#include <string>

//////////////////////////////////////////
//header
class Person {
private:
    std::string m_sID;
public:
    //constructor
    Person(std::string sID);
    //getter
    std::string getID() { return m_sID; }
    //setter
    void setID(std::string sID) { m_sID = sID; }
    void comparePersonID();
};

//////////////////////////////////////////
//implementation
Person::Person(std::string sID) {
    setID(sID);
}
void comparePersonID() {
    if (m_sID == "12345")
        std::cout << "success!" << std::endl;
}

//////////////////////////////////////////
//main
int main() {
    std::string myStr = "1";
    Person aPerson(myStr);
    aPerson.setID("12345");
    aPerson.comparePersonID();
}

Since comparePerson() is a member function of class Person, shouldn't it be able to access the private variable m_sID?

Or another way of asking the question: I know that in Ruby, you can get something like this to work by calling self.getID (or something thereabouts), but what is a working equivalent of self in C++ that compiles and executes properly.


Solution

  • comparePersonID is a member of Person, so the definition needs to be in Person's scope:

    void Person::comparePersonID() { ....
         ^^^^^^^^
    

    Otherwise it is just a declaration and definition of a non-member function which obviously cannot directly access the members of any class.

    Also note that getID() and comparePersonID() should really be const member functions.