Does operator overloading allows the access to private member without friend? [duplicate] - c++

class Person
{
private BankAccount account;
Person(BankAccount account)
{
this.account = account;
}
public Person someMethod(Person person)
{
//Why accessing private field is possible?
BankAccount a = person.account;
}
}
Please forget about the design. I know that OOP specifies that private objects are private to the class. My question is, why was OOP designed such that private fields have class-level access and not object-level access?

I am also a bit curious with the answer.
The most satisfying answer that I find is from Artemix in another post here (I'm renaming the AClass with Person class):
Why have class-level access modifiers instead of object-level?
The private modifier enforces Encapsulation principle.
The idea is that 'outer world' should not make changes to Person internal processes because Person implementation may change over time (and you would have to change the whole outer world to fix the differences in implementation - which is nearly to impossible).
When instance of Person accesses internals of other Person instance - you can be sure that both instances always know the details of implementation of Person. If the logic of internal to Person processes is changed - all you have to do is change the code of Person.
EDIT:
Please vote Artemix' answer. I'm just copy-pasting it.

Good question. It seems that object level access modifier would enforce the Encapsulation principle even further.
But actually it's the other way around. Let's take an example. Suppose you want to deep copy an object in a constructor, if you cannot access the private members of that object. Then the only possible way is to add some public accessors to all of the private members. This will make your objects naked to all other parts of the system.
So encapsulation doesn't mean being closed to all of the rest of the world. It means being selective about whom you want to be open to.

See the Java Language Specification, Section 6.6.1. Determining Accessibility
It states
Otherwise, if the member or constructor is declared private, then
access is permitted if and only if it occurs within the body of the
top level class (§7.6) that encloses the declaration of the member or
constructor.
Click the link above for more details. So the answer is: Because James Gosling and the other authors of Java decided it to be that way.

This works because you are in the class Person - a class is allowed to poke inside it's own type of class. This really helps when you want to write a copy constructor, for example:
class A
{
private:
int x;
int y;
public:
A(int a, int b) x(a), y(b) {}
A(A a) { x = a.x; y = y.x; }
};
Or if we want to write operator+ and operator- for our big number class.

Just my 2 cents on the question of why the semantics of the private visibility in Java is class level rather than object level.
I would say that convenience seems to be the key here. In fact, a private visibility at object level would have forced to expose methods to other classes (e.g. in the same package) in the scenario illustrated by the OP.
In truth I was not able neither to concoct nor to find an example showing that the visibility at class-private level (like offered by Java) creates any issues if compared to visibility at object-private level.
That said, programming languages with a more fine-grained system of visibility policies can afford both object visibility at object level and class level.
For example Eiffel, offers selective export: you can export any class feature to any class of your choice, from {NONE} (object-private) to {ANY} (the equivalent of public, and also the default), to {PERSON} (class-private, see the OP's example), to specific groups of classes {PERSON, BANK}.
It's also interesting to remark that in Eiffel you don't need to make an attribute private and write a getter to prevent other classes from assigning to it. Public attributes in Eiffel are by default accessible in read-only mode, so you don't need a getter just to return their value.
Of course you still need a setter to set an attribute, but you can hide it by defining it as "assigner" for that attribute. This allows you, if you wish, to use the more convenient assignment operator instead of the setter invocation.

Because the private access modifier renders it visible only within the class. This method is still IN the class.

the private field is accessible in the class/object in which the field is declared. It is private to other classes/objects outside of the one it is located in.

First thing here we have to understand is all we have to do is must follow oops principles so encapsulation is say that wrap data within package(i.e. class) and than represent all data as Object and easy to access. so if we make field as non-private than
it's accessed indivisually. and it result into bad paratice.

With reflection concept in Java is possible modify fields and methods privates
Modificando metodos y campos privados con Refleccion en Java

Related

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.

What is the role of private members?

#include<iostream>
class student
{
private:
int roll_no;
int standard;
public:
void input();
void display();
};
I asked my teacher about the significance of making some class members private and some members public. He said that data members are usually made private for security reason. He said that no object can access private things of a class, thats why they are secure.
My question is:
When we will develop software, we will be distributing executable files to users. Users will not be able to edit the code. What type of security our teacher is talking about? When I have created the entire code, how someone can edit it? What is the need to think about security?
No your teacher would not be correct that encapsulation, as this is called, is for security. Encapsulation is actually there for a few other reasons:
Creates better maintainability of code. When all the properties are private and encapsulated, it is easy for the writers of the code to maintain the program simply by changing the methods.
Have a Controlled Environment. Encapsulation lets the users use the given objects, in a controlled manner, through objects. If encapsulation didn't exist, client code could use the members of your class in any way they wanted, while member functions limit this to a specific behavior.
Hide Complexities: Hiding the complexities irrelevant to the users. Sometimes, some properties and methods are only for internal use and the user doesn't have to know about these. This makes it simple for the user to use the object.
An example that illustrates what would happen if you didn't have encapsulation:
Suppose you had a class called Human, with a member called age that is public. Now, if someone wanted to modify this, say, based off input, then they would have to check to see if the input is not negative or not a huge amount every time, unless they make a function for it. Now if there was a member function instead that provided access to age, then it wouldn't be client code's problem anymore, since the setter for the field would take care of it as it would be the responsibility of the class to make sure its fields are valid.
This will not affect users of an application, but the teacher is trying to make you safe from your own mistakes.
Keeping member variables private, when possible, protects you from accessing and changing them accidentally from places in your code where you shouldn't do that.
It also makes is clear for the users of the code which variables and functions are intended to be used from outside the class and which are not, thus clearly defining the API of the class.
Just like each person knows their own secrets and it is somehow dangerous to tell others, private members are not exposed to other classes because it may break something in the class and other classes don't really need to know them.
However, people need to communicate to fulfill their needs. We talk, explain our thoughts to be understood.. well, public members are like this, they are needed for the class itself communicate with other classes.

TDD in C++. How to test friend functions of private class?

if I have a class with a helper (private member) class within it, like this
class Obj;
class Helper {
friend class Obj;
private:
int m_count;
Helper(){ m_count = 0;}; // Note this is a private constructor
void incrementCount(){
++m_count;
};
};
class Obj {
Helper *m_pHelper;
// note that this is a private getter
int getHelperCount() { return m_pHelper->m_count; };
// the public API starts here
public:
Obj() { m_pHelper = new Helper(); };
void incrementCount(){ m_pHelper->incrementCount(); };
};
So how may I TDD such a system?
auto obj = new Obj();
obj->incrementCount();
// what to assert???
That is my question and the following is just some background.
Response to some answers and comments.
If noone outside the class should be interested, then your tests should not be interested either. – Arne Mertz
If nobody is interested in the value outside the class, why are you – utnapistim
Even if no one outside needs the value, I may still want to know that if it's set correctly, as it is used by other self contained internal method of the class that use that value. Maybe the value is the speed where the controller will use it to update the model. Or maybe it's the position where the view will use it to draw something on the screen. And in fact all other components of Obj would be able to access that variable. It may be a bad design issue, and in this case I would like to know what better alternatives I can have. The design is listed in the background section at the bottom of this post.
define private public - Marson Mao
Love this ingenious abuse of keywords haha. But may not be concluded as the best solution just yet.
You need to "expose" the friendship relation in the header of your class. Thus you have to acknowledge there the existence of a class used to test yours.
If you use the pImpl idiom, you could make the members of the pImpl itself all public, the pImpl itself private and give your unit tests access to the pImpl - CashCow
Does this mean that I should friend the test in my original class? Or add extra "test" methods to it?
I just started TDD very recently. Is it common (or better is it good) to intrude the original class with test class dependency? I don't think I have the appropriate knowledge to judge. Any advice on this?
Miscellaneous: AFAIK TDD is not just writing test, but instead a development process. I have read that I should only write tests to the public interface. But the problem is, like the situation in question, most of the codes etc are contained within private class. How may I use TDD to create these codes?
Background
FYI if you would like to know why I am making a private class:
I am developing a game from cocos2dx. The game engine adopts a Node tree structure for the updates, rendering etc and every game object would inherit from a Node class provided in the engine. Now I want to implement the MVC pattern on a game object. So for each object I basically created a Object class with 3 helper classes corresponding to each of the MVC components named ObjectModel, ObjectView, ObjectController. Theoretically no one should access the MVC classes directly and would only be accessed somehow through the Object class so I make the 3 of them private. The reason of making the MVC components explicitly as classes is because the View and Controller are updating at different rates (more specifically the Controller performs frame dependent updates, while the View do a simple interpolation based on the model data). The Model class is created purely for religious reasons lol.
Thanks in advance.
How to test friend functions of private class?
Thou shalt not!
A class (or module or library or whatever) exposes a public interface for a reason. You have the public interface (which is geared for client use, so it has invariants, preconditions, postconditions, side-effects, whatever - which can and should be tested) and implementation details, that allow you to implement the public interface, easier.
The point of having a private implementation, is that you are allowed to change it as you please, without affecting other code (without affecting even tests). All tests should pass after you change your private implementation, and client (and test) code should (by design) not care at all that you changed the private implementation.
So how may I TDD such a system?
TDD your public interface only. Testing implementation details means you end up coding to an implementation, instead of an interface.
Regarding your comment:
The problem is I don't even have a getter in the public interface. So how can my test check that the value is 0 or 1? And the getter is intentionally made private as no one should be interested in the value outside the class
If nobody is interested in the value outside the class, why are you (i.e. why would you wish to test for it?)
The #define private public trick can have side effects with the way some compiler are mangling function symbols (Visual c++ compiler is including access specifier in its name mangling)
You can also change visibility with the using statement :
struct ObjTest : public Obj
{
using Obj::incrementCount;
}
But like other people said, try to not test private stuff if possible.
I have encounter such problem when I was writing unit test as well.
After some searching I decided the most effective way is to add this in your Test.cpp:
#define private public
NOTE: add this before your desired include file, maybe your Obj.h, for example.
I think this method looks crazy but it's actually reasonable, because this #define only affect your test file, so all other people using your Obj.h is totally fine.
Some reference:
Unit testing of private methods
I vote, as #Marson Mao says, for #define private public.
If you want to control what to make private or public a bit more, you can do this in yourtests.cpp
#define private public
#include "IWantAccessViolationForThis.h"
#undef private
#include "NormalFile.h"
This way you can have a bit more control and try to do this trick in as few places as possible.
Another nice property of this approach is that it is non-intrusive, meaning that you don't need to clutter your real implementation and header files with #ifdefs for testing and not testing modes.
Your friend has full access to the class that it is a friend of. This might be done for many reasons and one of those could well be for unit-testing purpose, i.e. you want to be able to write a unit test that can call private members of the class and check the internal variables show what you would expect them to show, but you do not want that to be part of the public API.
You need to "expose" the friendship relation in the header of your class. Thus you have to acknowledge there the existence of a class used to test yours. No worries, you develop in the real world and classes are tested.
In order to write a unit test you will want to implement that class to provide protected member functions (probably static ones) that call all the relevant private functions or get the private members, and then you write classes that derive from yours. Note that those will not have direct access as friendship is not inherited, thus the static protected members.
If you use the pImpl idiom, you could make the members of the pImpl itself all public, the pImpl itself private and give your unit tests access to the pImpl (through the same model as above). This is now simpler as you only need to create one method for your "tester".
With regards to data members of a class, in recent years I have been known to put all these into a struct, i.e. have them all public, and then for the class to have a private instance of that struct. It can be easier for handling this kind of thing, and also serialisation / factories to your class, where they can create the struct which is all public, then construct your class from it.

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.

How should I order the members of a C++ class?

Is it better to have all the private members, then all the protected ones, then all the public ones? Or the reverse? Or should there be multiple private, protected and public labels so that the operations can be kept separate from the constructors and so on? What issues should I take into account when making this decision?
I put the public interface first, but I didn't always do this. I used to do things backwards to this, with private, then protected, then public. Looking back, it didn't make a lot of sense.
As a developer of a class, you'll likely be well acquainted with its "innards" but users of the class don't much care, or at least they shouldn't. They're mostly interested in what the class can do for them, right?
So I put the public first, and organize it typically by function/utility. I don't want them to have to wade through my interface to find all the methods related to X, I want them to see all that stuff together in an organized manner.
I never use multiple public/protected/private sections - too confusing to follow in my opinion.
Google favors this order: "Typedefs and Enums, Constants, Constructors, Destructor, Methods, including static methods, Data Members, including static data members."
Matthew Wilson (Safari subscription required) recommends the following order: "Construction, Operations, Attributes, Iteration, State, Implementation, Members, and my favorite, Not to be implemented."
They offer good reasons, and this kind of approach seems to be fairly standard, but whatever you do, be consistent about it.
Coding style is a source for surprisingly heated conversation, with that in mind I risk providing a different opinion:
Code should be written so it is most readable for humans. I complete agree with this statement that was given here several times.
The deviation is which roll are we taking about.
To help the user of the class understand how to use it, one should write and maintain proper documentation. A user should never be needing to read the source code to be able to use the class. If this is done (either manually or using in-source documentation tools) then the order in which public and private class members are defined in the source does not matter for the user.
However, for someone who needs to understand the code, during code review, pull request, or maintenance, the order matters a great deal - the rule is simple:
items should be defined before they are used
This is neither a compiler rule not is it a strictly public v.s. private rule, but common sense - human readability rule. We read code sequentially, and if we need "juggle" back and forth every time we see a class member used, but don't know its type for example, it adversely affects the readability of the code.
Making a division strictly on private v.s. public violates this rule because private class members will appear after they have been used in any public method.
It's my opinion, and I would wager a guess that most people would agree, that public methods should go first. One of the core principles of OO is that you shouldn't have to care about implementation. Just looking at the public methods should tell you everything you need to know to use the class.
As always, write your code for humans first. Consider the person who will be using your class and place the most important members/enums/typedefs/whatever to them at the top.
Usually this means that public members are at the top since that's what most consumers of your class are most interested in. Protected comes next followed by privates. Usually.
There are some exceptions.
Occasionally initialisation order is important and sometimes a private will need to be declared before a public. Sometimes it's more important for a class to be inherited and extended in which case the protected members may be placed higher up. And when hacking unit tests onto legacy code sometimes it's just easier to expose public methods - if I have to commit this near-sin I'll place these at the bottom of the class definition.
But they're relatively rare situations.
I find that most of the time "public, protected, private" is the most useful to consumers of your class. It's a decent basic rule to stick by.
But it's less about ordering by access and more about ordering by interest to the consumer.
I usually define first the interface (to be read), that is public, then protected, then private stuff. Now, in many cases I go a step forward and (if I can handle it) use the PIMPL pattern, fully hiding all the private stuff from the interface of the real class.
class Example1 {
public:
void publicOperation();
private:
void privateOperation1_();
void privateOperation2_();
Type1 data1_;
Type2 data2_;
};
// example 2 header:
class Example2 {
class Impl;
public:
void publicOperation();
private:
std::auto_ptr<Example2Impl> impl_;
};
// example2 cpp:
class Example2::Impl
{
public:
void privateOperation1();
void privateOperation2();
private: // or public if Example2 needs access, or private + friendship:
Type1 data1_;
Type2 data2_;
};
You can notice that I postfix private (and also protected) members with an underscore. The PIMPL version has an internal class for which the outside world does not even see the operations. This keeps the class interface completely clean: only real interface is exposed. No need to argue about order.
There is an associated cost during the class construction as a dynamically allocated object must be built. Also this works really well for classes that are not meant to be extended, but has some short comings with hierarchies. Protected methods must be part of the external class, so you cannot really push them into the internal class.
I tend to follow the POCO C++ Coding Style Guide.
i think it's all about readability.
Some people like to group them in a fixed order, so that whenever you open a class declaration, you quickly know where to look for e.g. the public data members.
In general, I feel that the most important things should come first. For 99.6% of all classes, roughly, that means the public methods, and especially the constructor. Then comes public data members, if any (remember: encapsulation is a good idea), followed by any protected and/or private methods and data members.
This is stuff that might be covered by the coding standards of large projects, it can be a good idea to check.
In our project, we don't order the members according to access, but by usage. And by that I mean, we order the members as they are used. If a public member uses a private member in the same class, that private member is usually located in front of the public member somewhere, as in the following (simplistic) example:
class Foo
{
private:
int bar;
public:
int GetBar() const
{
return bar;
}
};
Here, the member bar is placed before the member GetBar() because the former is used by the latter. This can result in multiple access sections, as in the following example:
class Foo
{
public:
typedef int bar_type;
private:
bar_type bar;
public:
bar_type GetBar() const
{
return bar;
}
};
The bar_type member is used by the bar member, see?
Why is this? I dunno, it seemed more natural that if you encounter a member somewhere in the implementation and you need more details about that (and IntelliSense is screwed up again) that you can find it somewhere above from where you're working.
In practice, it rarely matters. It's primarily a matter of personal preference.
It's very popular to put public methods first, ostensibly so that users of the class will be able to find them more easily. But headers should never be your primary source of documentation, so basing "best practices" around the idea that users will be looking at your headers seems to miss the mark for me.
It's more likely for people to be in your headers if they're modifying the class, in which case they should care about the private interface.
Whichever you choose, make your headers clean and easy to read. Being able to easily find whatever info I happen to be looking for, whether I'm a user of the class or a maintainer of the class, is the most important thing.
It is really helpful to the folks that will use your class to list the public interface first. It's the part they care about and can use. Protected and private can follow along after.
Within the public interface, it's convenient to group constructors, property accessors and mutators, and operators in distinct groups.
Note that (depending on your compiler and dynamic linker), you can retain compatibility with previous versions of a shared library by only adding to the end of the class (i.e. to the end of the interface), and not removing or changing anything else. (This is true for G++ and libtool, and the three part versioning scheme for GNU/Linux shared libraries reflects this.)
There's also the idea that you should order members of the class to avoid wasted space due to memory alignment; one strategy is to order members from smallest to largest size. I've never done this either in C++ or C though.
Overall, your public interface should come before anything, because that's the main/only thing that users of your classes should be interested in. (Of course, in reality that doesn't always hold, but it's a good start.)
Within that, member types and constants are best first, followed by construction operators, operations, and then member variables.
Put the private fields first.
With modern IDEs, people don't read the class to figure out what it's public interface is.
They just use intellisence (or a class browser) for that.
If someone is reading through the class definition, it's usually because they want to understand how it works.
In that case, knowing the fields helps the most. It tells you what the parts of the object are.
binary compatibility
There are a few concrete reasons for the ordering of class members.
These have to do with binary compatibility.
Binary compatibility mainly affects changes to system DLLs and device drivers.
If you're not interested in these, ignore this answer.
Public members must go before private members.
This is so you can mix and change private members without affecting the location of public data.
New public members must go last.
This again avoids affecting the position of existing public members.
The same ordering applies to vtable members.
Apart from this there's no reason to not to follow your own/your colleagues' preferences.
Depends entirely on your preference. There is no "the right way".
When doing C++ in my own pet projects I personally keep convention that I put access modifier before each member or method declaration.