C++ access specifiers - c++

I just want to make sure I got the idea of public and private right.
Regarding the private access specifier, does it mean:
Only accessed inside the class
Cannot be accessed from the object of the class unless there are public class methods that can be used to access them (Can other objects use those public functions?)
No other object can access them
And for public:
Accessed from the object of the class
Accessed from any other object
Is that right?

private : Only member functions and friends of class can access it.
public : Can be accessed anywhere where the object has scope.
Answering the questions -
private:
Yes
Yes. (Can other objects use those public functions? With out having class relations, one object of class cannot communicate to the other's members. )
Friends has access to private members of a class. So, answer depends upon your class has friends or not.
public:
Yes
Depends whether the object has hierarchical relations to the member's class you are trying to access.

I think there is an issue of vocabulary to begin with.
In C++ (and most languages) a class is a type. You can think about it as a blueprint to actually build something.
it describes the attributes that are held
it describes the methods to operate on those attributes
it describes the restrictions that apply: this is the "accessibility"
An object is produced by actually instantiating a class, that is, building what the blueprint described. It is more or a less a bundle of attributes. You can have several objects of the same class as you can have several houses from the same blueprint: note that their physical location is different for obvious reasons :)
Now, on to the accessibility. There are 3 typical levels of accessibility: public, protected and private.
public, as expected, means that everyone is given access to either attributes or methods
protected is somewhat less trivial. It means that only the object, or its children, may access the attributes (bad idea*) or methods. (Plus, in C++, friends)
private means that only the objects of that class (and not their children) may access the attributes or methods (Plus, in C++, friends)
Note: whatever the level of accessibility, an object has unrestricted access to all the attributes and methods of any object of the same class.
(*) Even though it pops up now and there, it is generally a bad idea to use protected attributes. The point of encapsulation is to hide the details, not only for the sake of it, but because by precisely controlling who can access the data, we can ensure that the class maintains its invariants (simple example, an array where you would store the size separately, you need to ensure that the "size" really represents the number of items in the array, at all times). Note: this restriction does not apply when you can seal a hierarchy, like in C# for example.

Private members can only be accessed by member functions and static functions of the same class and by friends of the class. It does not matter on which object that function is called. So the case
class Foo
{
private:
void bar() {}
public:
void baz(Foo& var)
{
var.bar();
}
}
is perfectly legal.

That seems correct. Data members and functions marked public can be accessed from anywhere by anyone. Data members and functions marked private can only be accessed by the class and its friends. However, a member function of a class can access data with any access specifier, so a public function can read and write private data members (this is used universally in OOP).

In c++ data and fn are encapsulated as 1 unit.
We begin a program by writing
preprocessor directives
Then, class declaration
Followed by function(fn) declaration where we also specify the access modifier ( public, private or protected)
& finally the main () program.
If we declare a fn
Private:the data within an object of a class is only accessed by fn defined within it- (the object which has the data and the private fn)
Public:the data can be accessed by any fn
Protected:similar to private however data can also be accessed by sub-classes that inherit the properties of another class.
Example if class A inherits from class B, thenA is a subclass of B.

Related

C++ How to add new functionality that shares mostly the same code?

I currently have a class that processes files on a local file system.
Class FileProcessor
{
public:
UpdateFiles();
private:
processFiles();
checkFileIsCorrupted();
}
Now, I want to add a new functionality, where the same file processing is done on files that first needed to be downloaded, but then it would call processFiles() and checkFileIsCorrupted() as before and do the same processing.
I'm wondering what's the best way to do this is.
I could change the interface for UpdateFiles() and add a parameter do determine whether I need to download the files, but modifying the public interface is clearly not ideal.
I could add a new public interface function UpdateFilesFromRemote() and thus share the private members, though this would seem to violate the single responsibility principle, which would call for the "new" functionality to be its own class.
Make a new class. This would either duplicate all the code in processFiles() and processData(), or require a new base class where processFiles() and checkFileIsCorrupted() are protected members,and all the private member they call on would also need to be moved to protected in this base class as well. However, from what I've read so far, most people seem to consider using protected to be something to avoid.
Make a new class and make processFiles() and checkFileIsCorrupted() friends of both classes. I'm assuming this would require both functions to take FileProcessor and the new class as objects (or a base class interface), so that the private members can be accessed. Although both FileProcessor and the new class would share many private members, and so that would still require them to be protected in the base class interface. Also, having a design where checkFileIsCorrupted() needs to take a FileProcessor object as input just... doesn't feel right. After all, its not actually modifying the FileProcessor object, its just a helper function to check if a file is corrupted.
Make a new class and make processFiles() and checkFileIsCorrupted() non member, non friend functions. This would mean that internal file information that is private to both classes would need to be passed as function parameters to these non-member, non friend functions, breaking encapsulation.
Either way, no solutions seems to be "good". Is there any better way to design this?
Thanks.

What is a public interface in C++ [duplicate]

What are public, private and protected in object oriented programming?
They are access modifiers and help us implement Encapsulation (or information hiding). They tell the compiler which other classes should have access to the field or method being defined.
private - Only the current class will have access to the field or method.
protected - Only the current class and subclasses (and sometimes also same-package classes) of this class will have access to the field or method.
public - Any class can refer to the field or call the method.
This assumes these keywords are used as part of a field or method declaration within a class definition.
They aren't really concepts but rather specific keywords that tend to occur (with slightly different semantics) in popular languages like C++ and Java.
Essentially, they are meant to allow a class to restrict access to members (fields or functions). The idea is that the less one type is allowed to access in another type, the less dependency can be created. This allows the accessed object to be changed more easily without affecting objects that refer to it.
Broadly speaking, public means everyone is allowed to access, private means that only members of the same class are allowed to access, and protected means that members of subclasses are also allowed. However, each language adds its own things to this. For example, C++ allows you to inherit non-publicly. In Java, there is also a default (package) access level, and there are rules about internal classes, etc.
All the three are access modifiers and keywords which are used in a class.
Anything declared in public can be used by any object within the class or outside the class,variables in private can only be used by the objects within the class and could not be changed through direct access(as it can change through functions like friend function).Anything defined under protected section can be used by the class and their just derived class.
A public item is one that is accessible from any other class. You just have to know what object it is and you can use a dot operator to access it. Protected means that a class and its subclasses have access to the variable, but not any other classes, they need to use a getter/setter to do anything with the variable. A private means that only that class has direct access to the variable, everything else needs a method/function to access or change that data. Hope this helps.
as above, but qualitatively:
private - least access, best encapsulation
protected - some access, moderate encapsulation
public - full access, no encapsulation
the less access you provide the fewer implementation details leak out of your objects. less of this sort of leakage means more flexibility (aka "looser coupling") in terms of changing how an object is implemented without breaking clients of the object. this is a truly fundamental thing to understand.
To sum it up,in object oriented programming, everything is modeled into classes and objects.
Classes contain properties and methods.
Public, private and protected keywords are used to specify access to these members(properties and methods) of a class from other classes or other .dlls or even other applications.
These are access modifiers.
All the data and functions(behaviours) are encapsulated or bounded into a single unit called a class. In order to access the properties and behaviour of the class we use objects. But it's also important to decide which behaviour or property has to be exposed or should remain accessible to all the classes and which behaviour or property has to be private.
So, that's when access modifiers like public, private, protected and protected internal help in doing so. This act of defining privilege to the class or method or property is called as abstraction.

using declarations for modifying access specifiers in derived class

One of the main design principles of C++ as an Object Oriented language is to let each class enforce who can access it's innards and who can't. A base class controls it's access levels even if it is with respect to a base class object embedded within a object of a class derived from Base.
However I read about using declarations that can be allowed to change the access level of a Base class member in a Derived class.
class A{
    protected:
    int n;
};
class B:protected A{
    public:
    using  A::n;
};
int main(){
    B obj;
    obj.n=0;
}
In the example above, I am changing the access level of a protected member to public in the derived class. Is this allowed on purpose? Why couldn't it be enforced that the access level should be more stringent or equal to how it is in the base class (this can be controlled by the access qualification in the derivation list as well) but cannot be more relaxed than the access level in the base class? Is this allowed because this allows some interesting design patterns? I am just trying to understood why something like this which breaks the principle of encapsulation enforced by a class is allowed?
One reason is that this way you can even change the visibility modifier even if you are not the owner of the base class.
For example if the base class is included in an external library/framework you can change the visibility modifier.

C++ subclass access

I have a main class that is inherited by numerous subclasses. The inherited main class has to be at least protected in inheritance to prevent non-derivative classes from using or altering it via the subclasses.
Is there a way to permit the various subclasses to alter each other's inherited main class variables, but without permitting public access to the main class? And without using the friend keyword given this would produce complicated code.
In full context:
I have a node class that add/remove nodes relative to it. There is a list class (and subclasses) that rely upon the node class, which means the node cannot be publicly accessible in-case it also breaks the class list. Node has to also be accessible to list helper classes.
To ensure that occurs, I implemented node under protected inside another class, accessnode. All classes wanting rights to node inherit accessnode as protected (so the accessnode class isn't public). This means the helper and the list class/subclasses all gain access to node.
The problem is, in order for TemplateList to copy CharList (a subclass of TemplateList) via read-only, it needs access to the nodes of CharList (to avoid using CharList's iterator) - the problem is, the nodes are protected (to prevent external, non-accessnode interference), and implementing a public method that grants access to the nodes would defeat the point.
What I need is sideways inheritance, so all subclasses of type accessnode can access each other's node without granting access publicly.
In short:
(Protected)Node inside AccessNode.
TemplateList : Protected AccessNode.
CharList : Protected AccessNode.
TemplateList needs to access CharList's AccessNode.
AccessNode/Node cannot be public.
Disclaimer: This is quite unrelated to this particular question, but more on the general problem that lead you to this and the other questions from today.
I think that you are barking at the wrong tree here. I get the feeling that you provide access to your list's internal nodes, and then expect that the node type itself protects the list from careless modifications (i.e. those that could break the invariants of the list). In doing so, you are pursuing a complex solution to a much simpler problem: do not let users access the node in the first place.
Things become much simpler if you look at the approach provided by the STL regarding containers and in particular lists. The list is implemented in terms of some unknown innaccessible nodes. The access specifiers on the operations of those nodes don't matter at all, since users cannot gain access to the object itself, so they can be public. Users gain access to the contents of the list through a different proxy (iterator, const_iterator types) that provides only those operations that cannot mess the state of the list.
I'm not completely sure I understand what you mean by "subclasses [to] alter each other's inherited main class variables".
If you want to allow access to a base class member variable by derived classes only then make the member variable protected. And/or add a protected accessor function.
If you want different instances of the derived classes to modify shared data held in the base class then you could add a static protected member variable to the base class. All instances would share the same member variable.
It would help if you clarified the problem.
You can always just add a protected accessor function in the top level class, but rather than do that it would probably be much better to rethink the design.
EDIT: concrete example:
class Base
{
protected:
struct State
{
int m1;
char m2;
State(): m1(), m2() {}
};
State state_;
static State& state( Base& o) { return o.state_; }
};
class Derived
: public Base
{
public:
void foo( Base& other )
{
Base::State& baseState = state( other );
// Blah blah.
}
};
int main()
{
Derived o;
// Blah blah.
}
Cheers & hth.,

How are classes more secure than structures?

Structure's member are public by default ans class's members are private by default. We can access private data members through a proper channel (using member function). If we have access to member functions we can read/write data in private data member, so how it is secure...we are accessing it and we are changing data too.....
Access specifiers, such as private and public have nothing to do with security. In C++, for example, these specifications get compiled away and don't even exist in the compiled binary.
Rather, access specifiers are designed to make types easy to use correctly, and difficult to use incorrectly.
There are only two syntactic differences between class and struct:
In a class, members and base classes are by default private, whereas in a struct, they are public by default.
For historical reasons, class can be used instead of typename to declare a template type parameter.
In fact, there's no difference between
struct X {
void f() {}
private:
int i;
};
and
class Y {
int i;
public:
void f() {}
};
The only way that a class is more "secure" than a struct is that it gently "presses" you towards better encapsulation by defaulting to private members.
There really was no need to introduce a new keyword class, Stroustrup himself said that on a few occasions. (Read his book The Design and Evolution of C++ if you're interested in such things.) Basically, class was introduced to emphasize the fact that a struct with member functions isn't really a "structure" anymore in the way the term was used in C: a collection of loosely coupled objects of built-in types. It's a "class" in the sense the term is used in statically typed object-oriented languages, even though syntactically, it's no real difference from a struct.
primarily because the member functions can validate the values before storing them. eg say you have a field called 'age', which must be between 0 and 150. in a structure (or a class with a public field), you could just do obj.age = 200. whereas if you only had a setAge(int) method, that method could sanity check the value is between 0 and 150 before storing, possibly throwing an exception if necessary or just clamping the value if not.
the public/private/protected keywords are not meant for security but rather for encapsulation. you design your class by separating the implementation (where the private/protected members are used - those actually used to implement the functionality) from the interface (where you expose the public members - which users of the class -other objects- will access/call) and thus you are later able to change the private parts without changing the interface. the outside objects only need to know about the public members and use these safely regardless of the implementation.
if you are speaking about security, think that anyone could change the private members of your class if they really wanted to and knew the internal structure of the class , just by overwriting the appropriate memory locations with new values - but the problem here is not about security, it's at a lower level
Taking that classes and structs are exactly the same besides the default access, the question is how encapsulating the internal representation from the interface helps build more robust code.
The main difference is that you control when and how your class data is modified, and as such you can control your class invariants. Consider a simple vector class that has a pointer and a size. By having them private you can control how they change: if the resize method is called, both the pointer and the internal size variable will be coherently updated, keeping the invariant that accessing any position in the range [0..size) is well defined. If the member attributes were public, user code would update the storage or size without actually updating the other field, and that invariant could be broken.
Many classes have internal invariants for the correct usage. If you write a class that contains a string with user email addresses, by providing an accessor method you can control that the value passed in is a valid email address, while if the email field was public user code could reset it to anything...
The whole thing is that you control how your members are accessed and modified and that reduces the number of places where mistakes can be made and/or your chances of detecting it.