How are classes more secure than structures? - c++

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.

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.

How should I share data structures

Bjarne Stroustrup: My rule of thumb is that you should have a real
class with an interface and a hidden representation if and only if you
can consider an invariant for the class.
On a current project, I had a base class called Widget. It had private variables for x, y, width, height (basically a rect data structure) and public getters and setters for each. Their was no purpose to the class except being a dumb variable holder. In light of Bjarnes' comment above, I got rid of this class, but I'm wondering how I should share this data structure with child classes that need them. Should I just individually include them as members for each class? Put them inside a Widget namespace?
You can use a struct
e.g.
struct widget
{
int x;
int y;
int w;
int h;
};
I'm not sure I entirely agree with Bjarne (aside from invariants the ability to change the representation may be an important concern although in that case it may be important to even move the actual definition into a PImpl rather than just making it private). However, you can group variables into a structure with public access to its members if there is no concern about changed members and or invariants. In case, the members are indeed just lumped together without a semantic meaning, you might even just use a std::tuple:
typedef std::tuple<int, int, double, double> widget;
... although in this case the different members do have access functions - for technical reasons independent from invariants and forward compatibility.
I think you massively misread Stroustrup there, let me emphasise the part that I think is important:
My rule of thumb is that you should have a real class with an interface and a hidden representation if and only if you can consider an invariant for the class.
I believe he is specifically not talking about not using the keyword class in this situation but is referring to a logical class (or "real class"). The difference is quite significant. A class (note the lack of markdown) is a data structure with a self contained interface and possibly a hidden implementation (see pimpl idiom). That means, the workings of a (logical) class are invisible to the user and a class object is communicated with via member functions and free functions. In terms of data abstraction that is sometimes interpreted as "don't access member variables from the outside" but that's just a shallower wording of the core idea.
You should still use structured design for heterogeneous collections of data just as you do (or as Commander or Dietmar Kühl suggests). Whether or not you use the class or the struct keyword is personal taste, but I tend to use the struct keyword so it is clear that this type is not a class in the logical sense but just some data that belongs together. I find using a proper struct is preferable to an std::tuple as you can name all the members, giving them meaning, rather than accessing them by index and having to remember what every index was supposed to mean. In addition it is easier to modify and extend a struct in the future.

c++ struct OO vs class OO [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What are the differences between struct and class in C++
class and struct in c++
It looks like that struct can has constructor and destructor and members, and looks very simple, so can we use struct instead class, if not, when shall we use struct with functions when shall we use class ?
https://github.com/developmentseed/node-sqlite3/blob/master/src/database.h#L32
struct Baton {
uv_work_t request;
Database* db;
Persistent<Function> callback;
int status;
std::string message;
Baton(Database* db_, Handle<Function> cb_) :
db(db_), status(SQLITE_OK) {
db->Ref();
uv_ref(uv_default_loop());
request.data = this;
callback = Persistent<Function>::New(cb_);
}
virtual ~Baton() {
db->Unref();
uv_unref(uv_default_loop());
callback.Dispose();
}
};
struct OpenBaton : Baton {
std::string filename;
int mode;
OpenBaton(Database* db_, Handle<Function> cb_, const char* filename_, int mode_) :
Baton(db_, cb_), filename(filename_), mode(mode_) {}
};
There's absolutely no technical reason to prefer one over the other, but I've noticed a certain convention regarding the use of class or struct.
If your datatype is something that is meant to be used by other parts of your program (ie. it's part of the 'interface'), then usually people make it a class to indicate its importance. If the datatype is used only in the implementation of a function or a class and it is not visible outside of a certain scope, then make it a struct.
These are some very rought guidelines, but no one will complain if you don't follow them.
Edit: In C++ there's no real difference between the two, but other newer languages that are inspired by C++ have actually made struct and class different. In C# and in D, for example, class and struct are both used to define datatypes, but they are not the same: struct is implemented such that it should be used for 'small' types.
The only difference is the default access-level (private for a class, public for a struct). Other than that, they are completely interchangeable. You should decide which one you like better, and use that all the time (consistency makes your code more readable).
when shall we use struct with functions when shall we use class ?
It is completely your choice.
There is nothing that one can do with classes and not with structures in C++.
Only difference between structure and class are:
access specifier defaults to private for class and public for struct
inheritance defaults to private for class and public for struct
So just use the one of your choice and stick to using it consistently, do not mix classes and structures.
While as stated by other struct & class does not have any difference besides default access level. However, it's common practice to use structs mostly for data aggregation, as that is what structs are reduced to in C. For example user defined PODs are almost always created as structs in my experience.
The only difference between class and struct is the default accessibility to its members and base classes. For struct, it is public and for class, it is private.
As others have said, the main difference is the default access level of member data and functions, namely private for class and public for structs. The same goes for default inheritance access levels: private for classes and public for structs.
As for when to use which, that is a matter of what is normal for the company to do. In my experience, most companies, and indeed individuals, use structs to hold packets of pure data and classes for storing a collection of functions that operate on its own data and/or structs.
This method is a throwback to C programming where structs can only store data and not functions and so most people like to stick to this definition in C++ too.
Note that it is common to use structs for functors, which would seem to break consistency through the code of structs not containing functions, but since functors usually only overload the () operator we retain some form of consistency anyway. Plus, it saves us having to type public for one function and/or inherited structures... Oh the typing we allow ourselves to avoid ;)
A class is a reference type. When an object of the class is created, the variable to which the object is assigned holds only a reference to that memory. When the object reference is assigned to a new variable, the new variable refers to the original object. Changes made through one variable are reflected in the other variable because they both refer to the same data.
A struct is a value type. When a struct is created, the variable to which the struct is assigned holds the struct's actual data. When the struct is assigned to a new variable, it is copied. The new variable and the original variable therefore contain two separate copies of the same data. Changes made to one copy do not affect the other copy.
In general, classes are used to model more complex behavior, or data that is intended to be modified after a class object is created. Structs are best suited for small data structures that contain primarily data that is not intended to be modified after the struct is created.

C++ access specifiers

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.

Class design with vector as a private/public member?

what is the best way to put a container class or a some other class inside a class as private or a public member?
Requirements:
1.Vector< someclass> inside my class
2.Add and count of vector is needed interface
If the container's state is part of the class's invariant, then it should, if possible, be private.
For example, if the container represents a three dimensional vector then part of the invariant might be that it always contains exactly 3 numbers. Exposing it as a public member would allow code external to the class to change the containers size, which in turn could cause problems for any routine which requires the container's size to be constant. Keeping the container private limits the places in your software where the container's size can be modified to the class's member functions.
Whether a member is declared Private or Public depends entirely on your application. Could you give some more detail?
One important point to remember when declaring your member is that if you provide a "getter" to retrieve it, then you are no longer encapsulating that object. Instead, it can be good to write wrapper methods exposing only the functionality you wish to expose.
For example, with a Vector member, you might write an AddItem and Clear method, if that's all the functionality you wish to expose.
Since you're talking about a class, I think it should be private. If you want it to be public, rather create a struct - to make it obvious that you want the members variables to be used.
A viable alternative to exposing the vector member is creating a visitor function (or an internal iterator). This way you obey the law of Demeter better:
class ContWrapper {
std::vector<int> _ints;
public:
class Action {
public:
virtual void accept( int i ) = 0;
};
void each_int( Action& a );
};
Also be very careful when exporting e.g. an std::vector<T> from a library, too: the client code might not use the same STL implementation as you did, so the layout of these member variables may differ!
Make all members private and use accessor methods, this allows you to change the implementation later. Only in very unusual circumstances would I make any data member public.
Remember that chaning the implementation happens more often than you may imagine, its not just a case of changing the type of the container but maybe you want to change the mechanism. Say you were storing names in a list, after a while you may chose to index this list with a hash and would like to have the hash updated every time you add a new name. If your implementation is suitably encapsulated doing this is easy, if you have just exposed the vector you would need to make changes that will adjust the interface (and so the change will ripple out).
If this is new to new you have a read of: http://en.wikipedia.org/wiki/Encapsulation_(classes_-_computers)
There is a third way - sometimes it is better to inherit from the container and override it's methods to achieve your goal (for example thread safety). Anyway, making it public almost always isn't a good idea.
Considering that you want to encapsulate the container inside another class implies that it cannot be public, and also the public methods of your class should not expose anything implementation-specific about the container. That way the implementation of your class (i.e. the container) can be changed without changing its interface.