Access Specifier in C++ - c++

I read the following statements from BRUCE ECKEL'S THINKING IN C++
1.Access specifier are part of structure and do not affect the object
created from "structure
Doubt:As we know the access blocks are not stored contiguously,
aint it that access specifier change the way object layout in memory
2.All of the access specification information disappear before the program is run
(during compilation).In a running program,object become the "region of storage"
and nothing more..thus we can break all the rules and access the memory directly
as you can in c
Doubt:Does it mean one can even access private member directly?please help me to comprehend the above statement
3.c++ is design to be pragmatic, not to aspire to abstract deal
Doubt:whats a meaning of being pragmatic?

1) Access specifier are part of structure and do not affect the object created from "structure"
Wrong actually, the order (in the layout) of data members within the same access specific (public, protected or private) is dictated by their order in the code, however no order is specified for data members with different specifiers.
class Foo
{
public:
int a;
int b;
protected:
int c;
int d;
};
The only thing we know is that a must come before b and c must come before d. abcd, acbd, acdb, cabd, cadb and cdab are all possible.
2) All of the access specification information disappear before the program is run
(during compilation).In a running program,object become the "region of storage"
and nothing more.. thus we can break all the rules and access the memory directly
as you can in c
The information is only used during compilation, but then compilation is what generate the running code. Therefore compilation ensures that you won't access private members. However, since direct memory manipulation is permitted, you could effectively access private members or functions if you wish, it's just highly error-prone to try and do it manually.
3) C++ is designed to be pragmatic, not to aspire to abstract the real
Pragmatic means that it's geared toward real use, with little consideration for purely theoretic arguments. Languages built from CS theory would include Haskell for example, which has an extremely sound mathematical background; on the other hand C++ has accumulated features that were deemed useful by its users.
Also, C++ does not hide the low-level details from you (like memory management). Good C++ code generally leave it up to the compiler and use idioms to try and abstract it (somewhat), but if necessary you can always get closer to the metal (even including Assembly code directly)... and sometimes (like memory management) you do have to pay attention to what you're doing.

class Foo {
int x, y;
public:
int z;
Foo(int a, int b) : x(a), y(b) {}
};
Foo foo;
You can get to the private member variables quite easily:
memset(&foo, int 0, sizeof(foo)); // wipes them all
fwrite(&foo, sizeof(foo), 1, fp); // dumps them to stream fp
As several commenters noted, this provokes undefined behavior under the C++ standard, so know your compiler before you attempt this (or better, don't). If you know how the compiler packs classes, you can even get more fine-grained access by hacks such as
struct PublicFoo {
int x, y, z; // order, padding, etc. depends on compiler
};
and casting a Foo * to a PublicFoo *. Nothing in the C++ runtime prevents that.

Related

Multiple access specifies good for machine-generated code?

In the second edition of "The C++ Programming Language", I read that we can have more than one private/public section of the class. However, allowing many access specifiers in a class is useful for machine-generated code?
I fail to understand how multiple specifiers are useful for machine-generated code? Can someone share deep insight to it?
However, allowing many access specifiers in a class is useful for machine-generated code?
To clarify: the book is referring to programs that output C++ code (rather than codegen in the sense of the quality of the generated output from the compiler).
A script that does that job is (very slightly) easier to write if, instead of having to sort members by access specifier and then output the result, you can simply write public/private as needed while you stream them out.
You could even do it for every member:
public: int a;
private: int b;
public: void f();
private: void g() { ... }
// etc.
which looks like other languages which have the specifier as an individual modifier of each member.

Is acceptable usage access specifiers before each member of class in C++

I write some code c++
public class SomeClass
{
private:
int m_CurrentStatus;
int m_PreviouseStatus;
public:
int get_CurrentStatus() { return m_CurrentStatus; }
int get_PreviouseStatus() { return m_PreviouseStatus; }
}
in c# style
public class SomeClass
{
private: int m_CurrentStatus;
private: int m_PreviouseStatus;
public: int get_CurrentStatus() { return m_CurrentStatus; }
public: int get_PreviouseStatus() { return m_PreviouseStatus; }
}
Such usage access specifiers before each member of class is acceptable?
Or can trouble compiler spend more time for compilation or other effects?
Code successfully compiled with no warning.
What you describe is legal C++.
The impact on compilation times will depend on the compiler. However, practically, you will probably be hard pressed to detect any difference of compilation times.
There may be either impact or benefit on code readability - i.e. ability of a human to understand what is going on. Generally, people prefer "sections" (e.g. the declaration of several members following a single access modifier (public, private, or protected)) quite well, as long as the sections don't get too large (e.g. fill more than a screen when editing the code). So doing it the way you are may be unpopular with other developers. This is highly subjective though - different people will have different preferences. However, if you find other people objecting to your approach, listen to them - unless you are happy to be unpopular with other team members, lose jobs, etc etc.
There may or may not be an impact on layout of data members in the class. Different versions of the C++ standard make different guarantees but there are considerable freedoms for compilers to lay out classes differently. If you are writing code that relies on (or tests for) particular class layout (order of data members, offsets, etc) you might observe a difference. Or you might not. However, these things are permitted to vary between implementations (compilers) anyway so writing code that relies on specific layouts is often a bad idea anyway.
It's legal syntax and shouldn't upset the compiler, you can have as many public and private blocks as you want. I don't see that it's an improvement syntactically though.
It's certainly legal and free from compile time penalties to put access specifiers before each and every class member. You could also put 50 semicolons at the end of every line. It simply isn't canonical C++.
It is Legal and also very correct. You won't use an object oriented language if you want to have your members public. A basic usage of object oriented programming is information hiding.
The only thing that can trouble compiler in your case(in a matter of time), is that your function block is inside the class.
What do I mean?
If you have a main.cpp and a class.h , and your functions are declared and defined inside class.h, your compilation will take a little longer, rather than if your function body was in functions.cpp
It's perfectly legal syntax for C++,
except for the public keyword before class
and the missing semicolon (;) after the closing curly bracket of class.
BUT I've never seen something like that, I suppose it's surely not commonly used and, in my opinion, it adds nothing to code readability (on contrary, I personally find it more cumbersome to read).

C/C++ Struct vs Class

After finishing my C++ class it seemed to me the structs/classes are virtually identical except with a few minor differences.
I've never programmed in C before; but I do know that it has structs. In C is it possible to inherit other structs and set a modifier of public/private?
If you can do this in regular C why in the world do we need C++? What makes classes different from a struct?
In C++, structs and classes are pretty much the same; the only difference is that where access modifiers (for member variables, methods, and base classes) in classes default to private, access modifiers in structs default to public.
However, in C, a struct is just an aggregate collection of (public) data, and has no other class-like features: no methods, no constructor, no base classes, etc. Although C++ inherited the keyword, it extended the semantics. (This, however, is why things default to public in structs—a struct written like a C struct behaves like one.)
While it's possible to fake some OOP in C—for instance, defining functions which all take a pointer to a struct as their first parameter, or occasionally coercing structs with the same first few fields to be "sub/superclasses"—it's always sort of bolted on, and isn't really part of the language.
Other that the differences in the default access (public/private), there is no difference.
However, some shops that code in C and C++ will use "class/struct" to indicate that which can be used in C and C++ (struct) and which are C++ only (class). In other words, in this style all structs must work with C and C++. This is kind of why there was a difference in the first place long ago, back when C++ was still known as "C with Classes."
Note that C unions work with C++, but not the other way around. For example
union WorksWithCppOnly{
WorksWithCppOnly():a(0){}
friend class FloatAccessor;
int a;
private:
float b;
};
And likewise
typedef union friend{
int a;
float b;
} class;
only works in C
I'm going to add to the existing answers because modern C++ is now a thing and official Core Guidelines have been created to help with questions such as these.
Here's a relevant section from the guidelines:
C.2: Use class if the class has an invariant; use struct if the data members can vary independently
An invariant is a logical condition for the members of an object that a constructor must establish for the public member functions to assume. After the invariant is established (typically by a constructor) every member function can be called for the object. An invariant can be stated informally (e.g., in a comment) or more formally using Expects.
If all data members can vary independently of each other, no invariant is possible.
If a class has any private data, a user cannot completely initialize an object without the use of a constructor. Hence, the class definer will provide a constructor and must specify its meaning. This effectively means the definer need to define an invariant.
Enforcement
Look for structs with all data private and classes with public members.
The code examples given:
struct Pair { // the members can vary independently
string name;
int volume;
};
// but
class Date {
public:
// validate that {yy, mm, dd} is a valid date and initialize
Date(int yy, Month mm, char dd);
// ...
private:
int y;
Month m;
char d; // day
};
Classes work well for members that are, for example, derived from each other or interrelated. They can also help with sanity checking upon instantiation. Structs work well for having "bags of data", where nothing special is really going on but the members logically make sense being grouped together.
From this, it makes sense that classes exist to support encapsulation and other related coding concepts, that structs are simply not very useful for.
It's not possible to define member functions or derive structs from each other in C.
Also, C++ is not only C + "derive structs". Templates, references, user defined namespaces and operator overloading all do not exist in C.
One more difference in C++, when you inherit a class from struct without any access specifier, it become public inheritance where as in case of class it's private inheritance.
C++ uses structs primarily for 1) backwards compatibility with C and 2) POD types. C structs do not have methods, inheritance or visibility.
Since nobody has mentioned it yet, there is actually another difference besides the default visibility. It turns out that class and struct are actually different things in MSVC.
class Vector2;
struct Vector2 {
double x;
double y;
};
This is 1 symbol on most compilers, but 2 different symbols on MSVC. Just this code by itself does compile fine. However, if you try to use it in more complex scenarios you will run into errors where this does not compile on MSVC because it gets confused about the symbols.

class member access specifiers and binary code

I understand what the typical access specifiers are, and what they mean. 'public' members are accessible anywhere, 'private' members are accessible only by the same class and friends, etc.
What I'm wondering is what, if anything, this equates to in lower-level terms. Are their any post-compilation functional differences between these beyond the high-level restrictions (what can access what) imposed by the language (c++ in this case) they're used in.
Another way to put it - if this were a perfect world where programmers always made good choices (like not accessing members that may change later and using only well defined members that should stay the same between implementations), would their be any reason to use these things?
Access specifiers only exist for compilation purposes. Any memory within your program's allocation can be accessed by any part of the executable; there is no public/private concept at runtime
Michael's answer is right. Access specifiers do not directly affect the resulting code.
However, access specifiers may resolve ambiguous identifier/overload errors that would otherwise prevent compilation.
class A {
private:
int x;
};
class B {
protected:
int x;
};
class C : public A, public B {
public:
int &get_x() { return x; } // only B::x is accessible, no error.
};
So they definitely serve a higher purpose than restricting the programmer.
The answer to your question could differ depending on the compiler, but in general there will be no difference. One could conceive though of an environment for which the compiled code might have different characteristics for those different accessibilities, but I'm not aware of any that exist.
Programmers can only make good choices when armed with the right information. Access modifiers are a way to signal to the programmer that certain things shouldn't be touched, and it has the side-benefit of enforcing correct behaviour.
There is no runtime impact. You could write a program with correct access modifiers, build it with, c++ -Dprotected=public -Dprivate=public file.cc, and it should build and produce almost exactly the same code (There are some hypothetical caveats such as data layout of classes).
Post-compilation, you are left with machine code (assembly) which has no notion of "public" or "private" (or of classes, members, etc). Everything is simply a memory address (whether it's code or data), and can be accessed just like any other memory address. The whole public\private distinction (as well as almost every other construct available in a high-level language) is purely for the benefit of the programmer, allowing the compiler to enforce a set of rules that are intended to make the intent of the code clearer and to help avoid potential bugs. Once compiled, your code doesn't know what language it was originally written in, much less what type of access specifiers were used.
That being said, it would be possible to rig a compiler so that it modifies the code whenever a private class member function is called in order to detect when the function is called inappropriately (add an extra parameter and set it to some expected value when the function is called from within the class; calling the function from outside of the class would provide the wrong value). The problem with this approach is what do you do now? Lock up? Do nothing and return invalid data? These types of problems are (relatively) easily detectable and correctable at compile time, so it is rare to see this sort of thing enforced at run time (outside of debugging or code profiling tools).

In C++ why is grouping not forced by the language on public, private and protected members of a class/struct?

Is it only to allow logical grouping?
It gives you flexibility. For example, you might have a bunch of constructors, some public, some protected, some private - wouldn't you want them all grouped together?
Why would you force it? It doesn't help the compiler out at all, it doesn't make things objectively easier for a person to read. Part of the C/C++ philosophy is that the language doesn't make arbitrary rules that don't enable some sort of feature/functionality.
It does make things MUCH easier for code generation. Many coding styles use access specifiers more than once per class - first defining all the local types, then all constructors, then all the methods, then all the instance variables, etc...
C++ gives you enough rope to shoot yourself in the foot, but it's that same flexibility that lets you build elegant, maintainable, and well abstracted applications.
I think you are correct. Leaving it unforced allows users to group things as they see fit for better code readability.
The compiler may organize things differently in memory.
edit: as per the spec:
§9.2 clause 12 (1998 and 2003 standards):Nonstatic data members of a (non-union) class declared without an intervening access-specifier are allocated so that later members have higher addresses within a class object. The order of allocation of nonstatic data members separated by an access-specifier is unspecified (11.1). Implementation alignment requirements might cause two adjacent members not to be allocated immediately after each other; so might requirements for space for managing virtual functions (10.3) and virtual base classes (10.1).
I found this information in a related SO question
My guess is that it is an outgrowth of the C philosophy, which assumes that you know what you are doing and gives you the maximum flexibility. It is like allowing a single = in an if statement.
I actually take advantage of this in a slightly unpleasant way: A code idiom I often use is a private member, with public accessor functions.
I have a MACRO (shudder) which automatically generates these from a single line.
example:
PROPERTY(int, MyVal);
...generates:...
private:
int fMyVal;
public:
void setMyVal(const int f) { fMyVal = f; };
int getMyVal() { return fMyVal; };
This works fine as long as you remember that the PROPERTY macro switches the current visiblity, which is not pleasant....
eg:
protected:
int v1;
PROPERTY (int, v2) // fv2 is private with public accessors
int v3; // whoops. f3 is public,
In "The C++ Programming Language, 3rd edition," Stroustrup says this is to make code generation easier.
Although it does make sense that the position of each field in the actual binary is based on which order that field was declared in the source code, so this allows somebody to maintain some sort of layout compatibility with C or even other languages/specs.