user3143781
user3143781

Reputation:

How to achieve encapsulation in C++ with getter method

In below code, I am assigning the value to url from another class function. I have received code review comment that 'Make url as private and implement getter function which should return the std::string value via an output parameter passed by reference'

class http_client
{
    public:
        std::string url;
};

I am confused with the above comment because I am using url only to set a value outside of http_client class. Initially, I thought that I have to make one public setter method which will set the value to url as shown in below.

class http_client
{
    private:
        std::string url;
    public:
        void set_url(const std::string& url)
        {
            this->url = url;
        }
};

Can anyone suggest what I am missing with above code review comment?

Upvotes: 1

Views: 92

Answers (1)

R Sahu
R Sahu

Reputation: 206657

The getter function is the counterpart of the setter. With the setter, client code is able to set the value. With the getter, the client code needs to be able to get the value.

I can think of couple of ways to do it.

std::string const& get_url() const
{
   return this->url;
}

void get_url(std::string& url) const
{
    url = this->url;
}

You are being asked to implement it using the second approach.

Upvotes: 3

Related Questions