Muhamed Shabani
Muhamed Shabani

Reputation: 23

Is it possible to access a Public Class Member from outside of the main() where it is created?

I am a newbie in c++ and today I was trying to make access a public class member outside of main(), more exactly in another function.

I tried to create pointer to that class, but I fail at accessing its members. I am going to show an example with a few lines of code, Any help would be appreciated.

Class City
{
private:
    string name;

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

bool isCity(string input)
{
    if(input== ???) { return true; } 
    return false; 
}

*The problem: how to access public member getName() from the class I create in main() at the question marks

int main()
{

    string input;
    City test;

    cin >> input;

    isCity(input);

    cin.get();
}

The pointer to Class is not working, the reference pass isn't working either.

Upvotes: 0

Views: 176

Answers (1)

Vuwox
Vuwox

Reputation: 2359

Easiest way is to have isCity part of the class and call it as a method of the object test.isCity(input);

The class should be as follow:

Class City
{
private:
    std::string name;

public:
    std::string getName() const
    {
        return name; 
    }

    bool isCity(const std::string& input) const
    {
        return input.compare(name) == 0
    }
};

Else you could have a free function (outside of the class), but the signature should provide the class city object as follow:

bool isCity(const City& c, const std::string& input)
{
    return input.compare(c.GetName()) == 0;
}

Which then means you have to call the function as follow:

isCity(test, input);

Upvotes: 2

Related Questions