Jump to content

C++ | Class Private Method

Hi P

I'm sure my question applies to other languages, but since I'm on C++ I thought I'd specify.

 

Question:

Could someone explain to me the real world use of private methods? or at least their purpose? at the moment is confusing.

 

Brief example code to explain my question:

(main and #include skipped, I'm on phone, please excuse my mistakes)

 

 

Class Person

{

Public:

    void set_name(string x)

    {

    return name = x;

    }

 

    void get_name()

    {

    return name;

    }

 

Private:

    string name;

 

};

 

 

By my understanding, I can store a value in the private attribute by using the public method set_name(), I can also access the value with get_name().

 

So if I can both, change and access the private attribute, what's the point of it being private? that's the confusing part.

 

The example is from the SoloLearn website, in case anyone wonders.

 

Thank you

 

Link to comment
Share on other sites

Link to post
Share on other sites

Private means it can only be accessed and changed from within the same class, public means any and all classes will be able to change the variable.

 

If you for example had three methods in one class:

Receive name

Verify name

Insert name into database

 

You wouldn't want any and all classes to access the latter two methods, because if they could just use the method to insert a name into the database, you wouldn't verify the name and bad things could happen.

 

Private means it can only be changed and accessed by the class it is in, which you use to make it so private things can't be used by everyone.

 

One could argue a class with no public methods would be useless.. because in that case no one could reach and thus use it.

 

"We're all in this together, might as well be friends" Tom, Toonami.

 

mini eLiXiVy: my open source 65% mechanical PCB, a build log, PCB anatomy and discussing open source licenses: https://linustechtips.com/topic/1366493-elixivy-a-65-mechanical-keyboard-build-log-pcb-anatomy-and-how-i-open-sourced-this-project/

 

mini_cardboard: a 4% keyboard build log and how keyboards workhttps://linustechtips.com/topic/1328547-mini_cardboard-a-4-keyboard-build-log-and-how-keyboards-work/

Link to comment
Share on other sites

Link to post
Share on other sites

1 hour ago, Hi P said:

<snip>

Yours is a very simple example and indeed, one can wonder if this should not be a simple struct:

struct Person
{
	std::string name;
	int age;
  	//etc...
};

However, it becomes more complicated if we have certain conditions to uphold, for example if we require a person to have a valid non-empty name and a sensible age. This is called the class's invariant.

class Person
{
public:

	Person(std::string name, int age) : 
		mName(std::move(name)), 
		mAge(age)
	{
		if (!VerifyName(mName) || !VerifyAge(mAge))
		{
			throw std::runtime_error("Tried to construct Person with invalid name or age!");
		}
	}
  
	int 
	GetAge() const { return mAge; }
  
	const std::string&
	GetName() const { return mName; }

private:

	std::string mName;
	int mAge;
};

In this example the Person's constructor requires a name and age to be given. The constructor checks if both the name and age are valid and if not throws a runtime_error exception, which aborts the creation of the class's instance. Thus, it prevents one from creating a invalid person.

 

The GetAge and GetName functions can only look at the name and age but not modify them. (GetAge returns a copy, GetName returns a const reference).

This, off course, requires name and age to be private. Otherwise anyone would be able to just write to them whatever they wish and break our invariant.

Link to comment
Share on other sites

Link to post
Share on other sites

If you would make all your private variables visible like that, there is no benefit of making them private.

But the huge advantage of making variables private is that you can add some logic to verify inputs or only allow read access to callers outside the class.

 

The purpose of the private keyword is to make sure that not everyone can access your data. Continue learning programming and you will see that it helps to bring a certain structure in your program and keep all your data safe.

 

Maybe read:

https://en.wikipedia.org/wiki/Encapsulation_(computer_programming)

https://stackoverflow.com/a/14399960

https://stackify.com/oop-concept-for-beginners-what-is-encapsulation/

 

Link to comment
Share on other sites

Link to post
Share on other sites

The benefits mentioned above are the primary ones, but another one worth mentioning is that if you provide getters and setters, it gives you the flexibility to change the way that the value is stored, without affecting the public interface. Suppose (for some reason) you change the implementation to use a char* rather than a string inside the data structure. If you're using public fields, now you need to change the code everywhere that you used it. With getters and setters though, you separate the interface from the implementation, so as long as you update the getter and setter you can change the implementation as much as you like.

HTTP/2 203

Link to comment
Share on other sites

Link to post
Share on other sites

8 hours ago, colonel_mortis said:

The benefits mentioned above are the primary ones, but another one worth mentioning is that if you provide getters and setters, it gives you the flexibility to change the way that the value is stored, without affecting the public interface. Suppose (for some reason) you change the implementation to use a char* rather than a string inside the data structure. If you're using public fields, now you need to change the code everywhere that you used it. With getters and setters though, you separate the interface from the implementation, so as long as you update the getter and setter you can change the implementation as much as you like.

Yeah you could do that but there aren't many cases you would do something like that. And if you do change the storage type, you have a good reason to do so and if your getter still returns the old data type you miss all the advantages of the new type (the new type should have advantages over the old typ - why else would you change?).

I don't see huge real world use for this. And I think I haven't seen it very often.

Link to comment
Share on other sites

Link to post
Share on other sites

10 hours ago, colonel_mortis said:

The benefits mentioned above are the primary ones, but another one worth mentioning is that if you provide getters and setters, it gives you the flexibility to change the way that the value is stored, without affecting the public interface. Suppose (for some reason) you change the implementation to use a char* rather than a string inside the data structure. If you're using public fields, now you need to change the code everywhere that you used it. With getters and setters though, you separate the interface from the implementation, so as long as you update the getter and setter you can change the implementation as much as you like.

While true, I'd advice against taking this too far. I would not go and take something that should clearly be a simple struct and make it's members private and add a bunch of getters and setters just in case things change.

 

There's enough refactoring tools these days to make those kinds of changes easily and quickly. And if a simple public data structure suddenly has to change into a invariant there's probably greater changes to worry about.

Link to comment
Share on other sites

Link to post
Share on other sites

Water down version is that it is for the purpose of encapsulation and to prevent code misuse. 

 

Until you understand the rationale, just take it for granted that you need to keep all instance variables private and use public getter and setters if you are to return or mutate them.

Sudo make me a sandwich 

Link to comment
Share on other sites

Link to post
Share on other sites

On 4/14/2019 at 6:35 AM, Unimportant said:

While true, I'd advice against taking this too far. I would not go and take something that should clearly be a simple struct and make it's members private and add a bunch of getters and setters just in case things change.

No, but it's far form unheard of to have said getters and setters defined in a purely virtual class.  It is a bit overboard for a PODO class, unless it contains some validation logic or needs to guarantee event callbacks are performed, or something else of that like...but especially in languages like C++ where you can avoid runtime dispatch and therefore let optimizer can cut out any of the additional complexity, its never bad practice to properly encapsulate data.

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×