Why Class Access Modifiers?

Go To Last Post
21 posts / 0 new
Author
Message
#1
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

You know, we have several Access Modifiers. Public, private, protected

But why we have use htem? I'm sure these features are so good and I have to use them but the question is why?

Just found a link about this question but it's complicated. everybody has said an odd and heavy thing. here is the link:

 

https://stackoverflow.com/questions/14414286/c-why-use-public-private-or-protected-inheritence

 

Please explain it in a simple manner as possible as and tell us What problem have you got so far and how did you solve that problem using Access Modifiers.

"One's value is inherent; money is not inherent"

 

Chuck, you are in my heart!

Last Edited: Thu. Aug 31, 2017 - 09:37 PM
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 2

You really need to get a good book about C++. If you don't understand data encapsulation you are missing one of the main reasons for C++. Nothing should be made any more visible /accessible than it needs to be.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

You know the FILE type from C? That struct whose members you are never supposed to access directly? But in C, nothing prevents you from doing it. In C++ you can say they are private. Then they will not be accessible.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

clawson wrote:
You really need to get a good book about C++.

+1

 

After watching the video that Paul linked to in another thread, I got inspired and had a look through some of the C++ books. I actively looked for where in the TOC the clas concept came in. Turns out, this is one where it comes in rather early: https://www.amazon.com/Tour-C-De... .

 

I aosl note that it is written with the intention to be an introductory text. According to Amazon it is published 2013, so with some luck it includes C++11. And it is by Bjarne himself - if you think that is a good thing.

 

Note that I have not read this book myself. Do read the readers reviews on Amazon! (I just might have to go down the basement and look in the C++ box to see if I own it..)

 

EDIT: No, not among the books in the C++ box..

As of January 15, 2018, Site fix-up work has begun! Now do your part and report any bugs or deficiencies here

No guarantees, but if we don't report problems they won't get much of  a chance to be fixed! Details/discussions at link given just above.

 

"Some questions have no answers."[C Baird] "There comes a point where the spoon-feeding has to stop and the independent thinking has to start." [C Lawson] "There are always ways to disagree, without being disagreeable."[E Weddington] "Words represent concepts. Use the wrong words, communicate the wrong concept." [J Morin] "Persistence only goes so far if you set yourself up for failure." [Kartman]

Last Edited: Thu. Aug 31, 2017 - 08:19 PM
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

clawson wrote:
You really need to get a good book about C++.

It sounds like has has got a book, but is just posting  the chapter headings as "Why do we need xxx?" threads ...

 

frown

Top Tips:

  1. How to properly post source code - see: https://www.avrfreaks.net/comment... - also how to properly include images/pictures
  2. "Garbage" characters on a serial terminal are (almost?) invariably due to wrong baud rate - see: https://learn.sparkfun.com/tutorials/serial-communication
  3. Wrong baud rate is usually due to not running at the speed you thought; check by blinking a LED to see if you get the speed you expected
  4. Difference between a crystal, and a crystal oscillatorhttps://www.avrfreaks.net/comment...
  5. When your question is resolved, mark the solution: https://www.avrfreaks.net/comment...
  6. Beginner's "Getting Started" tips: https://www.avrfreaks.net/comment...
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Rohalamin wrote:
Public, private, protected

Well, in 'C' we have scope - local, file, and global - don't we ... ?

 

 

Top Tips:

  1. How to properly post source code - see: https://www.avrfreaks.net/comment... - also how to properly include images/pictures
  2. "Garbage" characters on a serial terminal are (almost?) invariably due to wrong baud rate - see: https://learn.sparkfun.com/tutorials/serial-communication
  3. Wrong baud rate is usually due to not running at the speed you thought; check by blinking a LED to see if you get the speed you expected
  4. Difference between a crystal, and a crystal oscillatorhttps://www.avrfreaks.net/comment...
  5. When your question is resolved, mark the solution: https://www.avrfreaks.net/comment...
  6. Beginner's "Getting Started" tips: https://www.avrfreaks.net/comment...
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Rohalamin,

An absolutely essential pronciple of object-oriented programming is the concept of encapsulation.

 

The encapsulation concept is about separating implementation from interface. You might have many function in your class, only some of which are meant to be available to the user of the class, while others are just for internal use inside the class.

 

In that case it makes sense to have some mechanism to protect members of the class from being accesses from outside the class. This is done with the private access modifier. Of-course, if a member of the class is allowed to be accessed from outside the class there is a modifier public for that. In cases where inheritance is used, there might be cases where we would like to allow access to a member (in a superclass) from subclasses, but not from other classes - and there is an access modifier for that too; protected.

 

As with the other recent questions you've asked this is not so much about C++ specifically. Many object oriented languages support similar concepts, often with precisely those names (public, protected and private). The reason for having them is very much about software design rather than C++ programming specifically.

 


 

In another thread of yours today I used the example of a "circular buffer". It has operations to insert and extract chars to/from the buffer and it can be interrogated about the occupied space, if it is empty etc. All of this is done through member functions of the class, and they are public since the intention is that they should be calld from outside the class. But the phusical storage for the chars in this buffer, actually an array of chars, is not something that anyone/anything outside this class actually needs to see. Much less would it be allowed for anything outside  the class to manipulate this array of chars directly. It would destroy consistency of the inner state of this CircularBuffer. Thus the array is private, thereby protecting it from direct outside manipulation.

 

Here is such a class:

class RingBuffer {
public:
	RingBuffer()
		: inPosition(0), outPosition(0), length(0)
	{}

	void Insert(char c) {
		buffer[inPosition] = c;
		inPosition = (inPosition + 1) % bufferSize;
		length++;
	}

	char Extract() {
		char ret = buffer[outPosition];
		outPosition = (outPosition + 1) % bufferSize;
		length--;
		return ret;
	}

	int Length() {
		return length;
	}

private:
	static const int bufferSize = 8;
	char buffer[bufferSize];
	int inPosition;
	int outPosition;
	int length;
};

Notice that there are several things that must be done together at insertion or extraction. It is not enough to simply put things into the internal array or to take them out. We also need to keep track of where the next character should go in and where the next character should be taken out. So, the object has an "inner state" where the values of buffer, inPosition, Outposition etc all needs to be maintained together, and be kept consistent.

 

If anything outside of the class was allowed to access e.g. buffer directly it could eassily destroy the consistency of this "inner state" of the RingBuffer. Thus, we need a mechanism saying what things in thte object anything outside of it is allowed to access and not allowed to access.

 

And, as I said earlier, there is the case where we want to allow subclasses to access the inner state, but nothing else, and for that we have protected. No, I have no immediate small example of that.

As of January 15, 2018, Site fix-up work has begun! Now do your part and report any bugs or deficiencies here

No guarantees, but if we don't report problems they won't get much of  a chance to be fixed! Details/discussions at link given just above.

 

"Some questions have no answers."[C Baird] "There comes a point where the spoon-feeding has to stop and the independent thinking has to start." [C Lawson] "There are always ways to disagree, without being disagreeable."[E Weddington] "Words represent concepts. Use the wrong words, communicate the wrong concept." [J Morin] "Persistence only goes so far if you set yourself up for failure." [Kartman]

Last Edited: Thu. Aug 31, 2017 - 09:33 PM
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Rohalamin wrote:
Just found a link about this question but it's complicated. everybody has said an odd and heavy thing. here is the link:   https://stackoverflow.com/questi...

 

Note that the question in that SO thread actually is about access modifiers in the context of inheritance. This related to, but somewhat different than what I have talked about above.

 

Before I type anything further, to avoid any confusion and time bad spent, tell us:

 

Are you asking about access modifiers with respect to class members, i.e. the way I have used them in the example above, or are you asking about the use and reason in the context of inheritance - i.e. when they are used like this:

 

class FilteredRingBuffer : public RingBuffer {
 //                          ^
 //                          |
 // That one, there! --------+
 .
 .
 .
}

?

As of January 15, 2018, Site fix-up work has begun! Now do your part and report any bugs or deficiencies here

No guarantees, but if we don't report problems they won't get much of  a chance to be fixed! Details/discussions at link given just above.

 

"Some questions have no answers."[C Baird] "There comes a point where the spoon-feeding has to stop and the independent thinking has to start." [C Lawson] "There are always ways to disagree, without being disagreeable."[E Weddington] "Words represent concepts. Use the wrong words, communicate the wrong concept." [J Morin] "Persistence only goes so far if you set yourself up for failure." [Kartman]

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

JohanEkdahl wrote:
Many object oriented languages support similar concepts, often with precisely those names (public, protected and private).

Try it: put "Public, private, protected" into google - and see how many languages turn up in the results ...

Top Tips:

  1. How to properly post source code - see: https://www.avrfreaks.net/comment... - also how to properly include images/pictures
  2. "Garbage" characters on a serial terminal are (almost?) invariably due to wrong baud rate - see: https://learn.sparkfun.com/tutorials/serial-communication
  3. Wrong baud rate is usually due to not running at the speed you thought; check by blinking a LED to see if you get the speed you expected
  4. Difference between a crystal, and a crystal oscillatorhttps://www.avrfreaks.net/comment...
  5. When your question is resolved, mark the solution: https://www.avrfreaks.net/comment...
  6. Beginner's "Getting Started" tips: https://www.avrfreaks.net/comment...
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Thank you, Mr.Ekdahl but everything you said so far, I can see in my book.

It apears I couldn't explain to you what's my question exactly. The main question come up after you say:

Much less would it be allowed for anything outside  the class to manipulate this array of chars directly.

What in the world would touch your array when your code is runing? Our code? How? When we are writting our code, we know we must not touch that array. Is there anything else that could access it without our permission? our code? how?

JohanEkdahl wrote:

 

Note that the question in that SO thread actually is about access modifiers in the context of inheritance. This related to, but somewhat different than what I have talked about above.

 

Before I type anything further, to avoid any confusion and time bad spent, tell us:

 

Are you asking about access modifiers with respect to class members, i.e. the way I have used them in the example above, or are you asking about the use and reason in the context of inheritance - i.e. when they are used like this:

 

class FilteredRingBuffer : public RingBuffer {
 //                          ^
 //                          |
 // That one, there! --------+
 .
 .
 .
}

?

Both

"One's value is inherent; money is not inherent"

 

Chuck, you are in my heart!

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

awneil wrote:

It sounds like has has got a book, but is just posting  the chapter headings as "Why do we need xxx?" threads ...

 

frown

Andy, I think some books are written for users who are familiar with OOP and then they skip some points and they just talk about that language.

 

"One's value is inherent; money is not inherent"

 

Chuck, you are in my heart!

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 1

Rohalamin wrote:
What in the world would touch your array when your code is runing? Our code? How? When we are writting our code, we know we must not touch that array. Is there anything else that could access it without our permission? our code? how?

 

This is an important thing that you have not yet recognized. One of the BIG things about C++ is "code reuse" which includes "code sharing". Assume that other people are going to use your code and they may not know the details that you do. For that matter, think of yourself trying to reuse a class a year after it was written. Do YOU remember all of the details that you know now?

 

Jim

Jim Wagner Oregon Research Electronics, Consulting Div. Tangent, OR, USA http://www.orelectronics.net

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 1

Rohalamin wrote:
What in the world would touch your array when your code is runing? Our code? How?

By ways of bad programming, i.e. someone planting a bug. With your reasoning we would not need the const specifier in C, we would not need the type system at all. With your reasoning no-one ever makes a mistake, or sees an opportunity to be lazy and take a dangerous shortcut when the opportunity is there.

 

Rohalamin wrote:
When we are writting our code, we know we must not touch that array.

How do we know that? My example is close to trivial. Imagine a more complex class where it is not obvious that you should not access a certain member (be it a data member or a member function). And remember that it is common for someone to use a class that he has not written himself. How would how would that person know that he should not access the member directly? By a comment or some documentation? Why not create a concept in the language that guarantees that the member can not be accessed?

rce

Do note that it is such a common notion that members should be private unless they are specifically written to be public that the default access modifier in a class is private. I.e. if you do not explicitly write any access modifier the members will become private.

 

I believe that you underestimate the complexity of many real time software systems. A code mass that is, say 50 K lines of code (with blank lines and all-comment lines removed) is perhaps double that with blank lines and comments. What does that mean? Well, for example, if you print it out with 50 lines per page that would be 2 K pages. That is like a really thick book! With tat kind of code mass, there is no way you can keep everything in your head. Instead you rely upon a few principles/techniques:

 

1) Documentation, in some sort.  Many favour documentation written in the source files and then extracted with some tool into e.g. HTML documents that can be browsed through with relative ease.

 

2) Well written code that "documents itself" to the largest extent possible. This is in part about picking good names etc. But it is also about expressing, in some way, the intent of the code. Why not have a construct in the language itself that supports expressing such intent. I want to say "Hey, user of this class! You are not supposed to access data member x - it is for internal use in the class only", or "You are not supposed to call function f - it is for use internal to the class only". It is just a fact that many OO languages have such a construct, and that they have chosen to name it private. A sensible choice, in my opinion.

 

Another way of looking at it: How many members are there in the string class? Which of them can you access safely without disturbing the inner state of the object?

If you answer "It's in the documentation" then my follow up is "How do you think it got there?" How does the documentation know which methods of a class is safe for a user to call and which are not? Because someone put the access modifier public on them, amd the automated documentation generator knew it should extract those method names (and their parameters etc) into the documentation.

 

A general observation:

It seems to me that you are vigorously arguing against what C++ has to offer. I suggest you perhaps do not study it, because with that attitude nothing good will come out.

 

But.. If you prevail: Whatever you want to learn, the attitude should be a positive curiousness - that makes for a better learning experience and result. Also, and I've mentioned this before, since we are talking about one of the more complex programming languages be prepared for this to be a much longer learning experience that learning C. Especially since you seem to want to learn everything down to the details on the first run through it.

 

Another question: How much code have you read? How much code have you written? I often say that learning to program, or learning a completely new  programming language, is like learning to ride a bike. You can read all the books you want, but it will not make you able to ride a bike. You can watch others ride a bike, but.. You have to get up on the bike yourself!

 

Regarding the passing of time: Since you are not versed in object-oriented concepts in general (the encapsulation question clearly reveals this) you have (at least) two things to learn at the same time. OO in general, and C++ in particular. Prepare to spend many months. I came from about 15 years of mainly Pascal and C when I encountered C++. It took me a year before I was getting comfortable with C++ and few years to be really comfortable with OO. Be realistic, this will take time.

 

Read a lot of code.

 

Write a lot of code.

As of January 15, 2018, Site fix-up work has begun! Now do your part and report any bugs or deficiencies here

No guarantees, but if we don't report problems they won't get much of  a chance to be fixed! Details/discussions at link given just above.

 

"Some questions have no answers."[C Baird] "There comes a point where the spoon-feeding has to stop and the independent thinking has to start." [C Lawson] "There are always ways to disagree, without being disagreeable."[E Weddington] "Words represent concepts. Use the wrong words, communicate the wrong concept." [J Morin] "Persistence only goes so far if you set yourself up for failure." [Kartman]

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 1

Languages like C++ were invented so people could write very big programs that would be too complex for the programmer to understand if written in a language like C.  So the modularity and things like private/public are very important.  For small programs they might be overkill.

 

I've seen C programs so complex that people were afraid to make any changes for fear something would break.

 

For small programs, if you fail to mark private things private, nothing bad should happen, unless your a really bad programmer.  And if something bad happens, you can always go back and do it according to the book.

 

If all programs were small, C++ and other OOP stuff wouldn't have been invented.  Personally I'm glad they were invented so I can use it in just about all programs.  

Last Edited: Fri. Sep 1, 2017 - 10:08 PM
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

people could write very big programs that would be too complex for the programmer to understand

Just look at windoze-- could one programmer even know 1% of its nooks & crannies?   You simply must have some level of control when there are 1000 people mixing their code into one interconnected stew.

When in the dark remember-the future looks brighter than ever.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 1

Think of it this way:  C is a language with very few "rules."  Where assemblers of the day had "macros" with obscure syntax and powerful capabilities, C has a pre-processor that doesn't do anything more than text substitution.  Where BASIC had easy-to-use strings, C gave you unbounded arrays of characters.  Where some languages carefully differentiated between language data types and user-defined structures, C lets you fetch and dereference pointers to anything, possibly re-interpretting what they point to on the way.
 

This is all very powerful.  Together with the lack of much in the way of a standard runtime environment, it lets C be ported to new processors much more quickly, and that has let it spread across a wide range of targets...  You couldn't do "#define PORTB (*(uint8_t *)(0x5))" in most languages.

 

Over the decades, lots of people have done lots of stuff with C.  And they've begun to recognize which things that have been done have been particularly dangerous or troublesome, and they've created new languages (including C++) that include capabilities that allow you avoid (or FORCE you to avoid) many of those dangerous things.  They don't always do anything that you couldn't have done anyway, with careful attention to "internal standards" and good documentation, but they make it easier than that.

Consider:

struct tty_ {

// public data that the user can change

    int public_length; int public_width; int public_speed;

// private data used by the driver; don't touch if you're not the driver!

    int private_bufferhead;  int private_buffertail;  int private_buffercount;  int private_buffersize;

} tty;

That's clear enough.  It MIGHT be sufficient for most purposes.  Only an idiot would do something like:

tty.private_bufferhead=tty.private_buffertail=tty.private_buffercount = 0; // quick buffer clear with no driver overhead!

Alas, the world is full of idiots.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 1

Rohalamin wrote:
I think some books are written for users who are familiar with OOP and then they skip some points and they just talk about that language.

So get yourself some OOP books, then!

 

As has been pointed-out many times, much of what you're asking is just basic OOP principles - nothing specifically to do with C++ (or any other language).

 

In fact, several of your questions seem to betray a fundamental lack of understanding of the basic principles structured programming - like the basic idea of scope.

 

Top Tips:

  1. How to properly post source code - see: https://www.avrfreaks.net/comment... - also how to properly include images/pictures
  2. "Garbage" characters on a serial terminal are (almost?) invariably due to wrong baud rate - see: https://learn.sparkfun.com/tutorials/serial-communication
  3. Wrong baud rate is usually due to not running at the speed you thought; check by blinking a LED to see if you get the speed you expected
  4. Difference between a crystal, and a crystal oscillatorhttps://www.avrfreaks.net/comment...
  5. When your question is resolved, mark the solution: https://www.avrfreaks.net/comment...
  6. Beginner's "Getting Started" tips: https://www.avrfreaks.net/comment...
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

You really need to get a good book about C++. 

Could a link to http://www.cplusplus.com/  work? (can be put into a "smart" "phone", wit a speech/songs synthetiser to keep the phone functionality)

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Now this thread has been revived I'd like to add a reference to the Standard C++ Foundation:

https://isocpp.org/

https://isocpp.org/search/google...

 

And the "well trodden road" of typing C++ in your favourite search engine combined with "course" / "learn" / "book" / "reference" / "online" / etc.

Sorry for the over generalisation, but I've learned that people are not the same.

Different people learn in different ways.

Spend some time on diffent websites first and then choose something that fits your style / knowledge level / interests.

 

Also, keep in mind that C++ is an evolving standard. C++20 is being worked on now.

https://isocpp.org/std/status

Paul van der Hoeven.
Bunch of old projects with AVR's:
http://www.hoevendesign.com

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Paulvdh wrote:
choose something that fits your style / knowledge level / interests.
yes

David (aka frog_jr)

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

The reason features like “protected” exist is that they are needed. They aren’t there to satisfy some academic “cool idea”. They are there because without them we had total chaos. I witnessed it many times. For decades we used languages that had no such annotations, and “clever” programmers figured out how to “twiddle” parts of the data structure to get the “desired” effects. I had to go to great effort in C to prevent people from messing with or depending upon implementation details that were none of their business. This allowed me to, at various times, rewrite the innards of the code to make it run faster, or use less memory, or both. Your question causes me to infer that you haven’t written very much code. When you get more experience, work on teams building large systems, create libraries for others to use, and have written a few hundred thousand lines of code, you will wonder why any mechanism as weak as public/private/protected could ever have been thought of as a sufficient solution to the problem.

I speak from 54 years experience, and for most of those years, it was a bad year if I only wrote 100,000 lines of code. public/private/protected was a good start in 1967 (Simula-67 introduced these ideas), but our needs now are vastly more complex, and the languages have not evolved to meet them.

With any luck, by the time you enter mainstream programming, you will face much more sophisticated interface controls that begin to approximate solutions that we need. But if you try to create C++ code that is essentially C code, you will be in trouble. Programming standards & practices documents of major corporations have non-negotiable requirements. If you don’t understand the basic concepts, the time to learn them is not after you have been hired, but now.

Note that within Microsoft it is said to be a firable offense to write a strcpy() call in any code. Instead, s_strcpy() must be used, because it takes a maximum length. It is also a firable offense to pass in the pointer to a buffer and not pass its length.

And remember: the code you write will be maintained by unskilled labor. That means the New Hire, or yourself six months later. I’ve had code that I wrote come back to me three to ten years after I wrote it, with requests like “extend this code to support our new line of controllers” or “one of our customers needs this new logging feature added”. Like my reaction when I get old code back, yours should be “who wrote this crap?” And then a great sigh of relief when you discover those extensive ASCII-art data structure diagrams you put in (after ten years, I had no memory of what they were). The first reaction tells you that you are maturing as a programmer. The second reaction demonstrates that you were already a skilled professional when you wrote that code.

Last Edited: Sat. Feb 24, 2018 - 01:49 AM