Can there be two public section in a class? If yes then why ? And in which circumstances we do so? - c++

There is something bugging me about classes. For example
class A
{
public:
A()
{
.....
.....
}
void cleanup()
{
....
....
....
}
public:
UINT a;
ULONG b;
};
In the above example there are two public section. In the first section I am defining a constructor and a method and in the second section I am declaring data members. Is the above class i.e. A correct. Can we do that? If yes then why is that needed and in what circumstances should we use it? Since we can do the entire thing in one section then why are there two sections?

Access qualifiers simply apply to the code that follows until the next qualifier. There is no restriction on the number or order of such qualifiers.
It is generally not necessary to repeat the same access qualifier in a class, and doing so is likely to confuse the reader. They also may have an effect on the layout of a class, since data members following the same qualifier must be laid out in the order they are declared, but there is no such restriction between qualifiers.

As Marcelo says, you can use the public, private and protected qualifiers as many times as you wish. "When" is entirely personal. Some people like this:
class AClass
{
public:
// all the public stuff
protected:
// all the protected stuff
private:
// all the private stuff
};
but personally (and this really is just a personal preference) I like to do this:
class AClass
{
// constructors and destructors
public:
// public cons/dest
protected:
// protected cons/dest
private:
// private cons/dest
// accessors
public:
protected:
private:
// methods
public:
protected:
private:
// members
public:
protected:
private:
};
Feel free to come up with your own style, whatever you're comfortable with. There is no right or wrong way of doing it. Just try to be consistent.

Yes its correct however personally I prefer to just have one public section at the top of the class, that's where programmers looks first when examining a new class. It is then easier to see which parts are supposed to be accessible and which are not -- instead of browsing the whole class header.

I usually try to arrange the declaration of the class so that it's easy for others to use the said class.
The usual is thus: public/protected/private, in this order, because it simplifies life for the readers.
People who use the class can stop reading once reaching the protected tag, anything after is none of their concern.
People who derive from the class can stop reading once reaching the private tag, anything after is implementation detail.
This, coupled with not writing the code of the methods at their point of declarations, makes for an easy to read interface.
There are however a couple of tricks:
when using metatemplate programming, you may need to declare types first, methods afterward, so you end up with 2 series of public/protected/private
when using the Key idiom (instead of friend), you have a public section that is in fact dedicated to only a small portion of the users and is best isolated either at the bottom of the normal public section or after the protected section.
Finally, as to comment about the layout issue among the attributes. Encapsulation means that attributes should be private. So, either you have a struct and everything is public or you have a class and everything is private, mixing the two means breaking encapsulation, and that's a bug in the making.

The class is correct, public is just a access qualifier and will apply till the next qualifier is seen or the end of class declaration. There is no limit to how many of these access qualifiers(public, private, protected) you can have in a class. As to why this is useful, it helps writing class declarations the way you want. For example I might want all the member functions (public,protected or private) declared before the (say) private data members.

As #Marcelo Cantos's answer explains, this is allowed. When writing code yourself you should avoid this, as it only leads to confusion when others read your code. The only place I have ever seen this in real life is in the code generated by various MFC-wizards. Whenever you add some thing to your class using a wizard, it would just add an extra section to the end of your class.

Related

Granting access on a function to another class without exposing it

I have a class let us call it Person:
class Person{
private:
void move(x,y,z);
}
I have another class called PersonController:
class PersonController{
public:
void control(){
while(some_thing){
//do some calculations
controlled_person_->move(some_values); //Wrong Accessing to a private member
}
}
private:
Person* controlled_person_;
}
Both Person and PersonController are part of the public interface of the library I am designing.
I want PersonController to be able to call move from Person. However, I do not want anyone to access this function (move) from the public interface.
The easy way to sovle the problem is add a friendship so PersonController can access private members of Person. However, as far as I read the friend keyword was not introduced to solve these kind of problems and using it here would be a bad practice.
Is this correct? Should I avoid friend here?
Does this mean my design is broken?
Any alternative suggestions?
From what you said in comments, it seems you are interested in only allowing PersonController to touch that one member function. The way to do that and only that, is to make the door public, but add a private key for it:
class Person{
public:
class MovePrivilege {
move_privilege() = default; // private c'tor
friend class PersonController; // only PersonController may construct this
};
void move(MovePrivilege, x,y,z);
};
class PersonController{
public:
void control(){
while(some_thing){
//do some calculations
controlled_person_->move(MovePrivilege{} , some_values);
}
}
private:
Person* controlled_person_;
};
The type MovePrivilege has a private c'tor. So it can only be constructed by its friends. And it is also required for calling move. So while move is public, the only classes that may call it are the friends of MovePrivilege.
This essentially gives you a fine grained control over who may call move. If this is obtrusive and you can't change move itself, a variant of the attorney client idiom may be appropriate instead.
You do have options at your disposal. Direct firend-ship is just the bluntest tool.
That is exactly the sort of problem that friend is meant for. While friendship should be minimized if your design needs it there is no reason not to use it.
I see non-use of friend a lot like the continuing dislike of 'goto', there are simply times where using it will make a design far cleaner.
Yes your design is not correct.
Classes are an expanded concept of data structures: like data structures, they can contain data members, but they can also contain functions as members. You can read more here
So PersonController (If it only control person class) should not be a class because it is not concept of data structures Check if it is possible to merge them or design another way.
There are many ways to do it.If you want to design it like what you do now you can use protected access controller for your function and Create derived class but it's not a good design again.
You can use friend function here too but it isn't an object oriented concept again(But the easiest way).
You should rethink about your design if you want to design it OO.Because you can't access private function from other class in object oriented programming ,It breaks encapsulation so C++ won't let you do that.
However your question depends on opinions too.

Determine if method or member can be protected or private

It is possible to check (for example by gcc) which methods or members can be moved to protected or private section?
Consider the following part of code:
class foo{
protected:
void foo_method_1(){};
int foo_member_var;
};
class bar : public foo{
void bar_method_1(){
foo_method_1();
}
};
If you want to determine which members and methods of the foo class can be private, you have to move all of them to the private section. So it will look like this:
class foo{
private:
void foo_method_1(){};
int foo_member_var;
};
...
Now it won't compile, here's the first error thrown by GCC:
prog.cpp:5:8: error: 'void foo::foo_method_1()' is private
void foo_method_1(){};
From that you know, that you have to move the foo_method_1 to the protected section. So it will look like this:
class foo{
private:
int foo_member_var;
protected:
void foo_method_1(){};
};
...
Now it will compile. You have to repeat this process for every single method and member in your class. For public section you can do it in the same way as described above.
You can't do this programmatically, no. And that's actually a good thing.
Sure, you could create a tool that integrated with a C++ parser, then — one-by-one — made certain members functions private and left any there that didn't cause an error in your program.
But, in order to do that, your entire program would need to be visible to that tool. Maybe if you have a simple project that's not a problem, but if you're writing a library that's literally impossible.
Even if you could do it, your resulting class design would be an absolute mess. Only a human programmer knows which parts of the API are designed for public consumption or not, and that's not always the same as which parts of the API are currently being consumed.
Stick to the manual approach, but don't just replicate the way the machine would do it, randomly guessing based on what compiles and what does not compile. Use your brain and your memory of what this class is supposed to do, to determine which functions should be public and which should not.
Ideally, try to get it right when you're first designing your class! You should be spending far more time designing your program than actually programming it, lest you very quickly end up with maintenance nightmares like this.
No. The compiler sees your code, not your design.

using same C++ access specifiers multiple times

What is the purpose of declaring multiple "public" specifiers over and over again when the next line is just right below it, or few lines below it. I can understand this is requirement when the codes modified the attribute of some identifiers, i.e., those that are buried within a macro (hence changing the access attributes within the macro, so we need to "redefined" coming out of the macro), or when we have many identifiers per access specifier section. But what is the purpose of keep using "public", "public", over and over again?
Code ...
class CDrawMFCView : public CView
{
protected: // create from serialization only
CDrawMFCView();
DECLARE_DYNCREATE(CDrawMFCView)
// Attributes
public:
CDrawMFCDoc* GetDocument() const;
// Operations
public:
// Overrides
public:
virtual void OnDraw(CDC* pDC); // overridden to draw this view
virtual BOOL PreCreateWindow(CREATESTRUCT& cs);
protected:
// etc.,
};
For starters, it's not necessary for how the code is NOW, it's necessary because the code sections may:
become a lot longer
be cut-and-pasted into a different order, or even into a different class, or copied into a new class
have some sections change the access specifier without the previous or following ones changing
If you relied the section having the same access specification as the previous section, very very often you (or you, six months from now, or someone else) would forget to change it when the code changed, and then the code would be wrong.
It could be useful when looking at a class with more methods than lines on your screen, so you just look at, say
...
void f();
void g();
void h();
...
By repeating public: a few times you could remind people that all these are public (of course, having more methods than lines in your terminal either means your terminal is a bit small or the class is too big).
There is only one formal reason: data members between access specifiers are ordered sequentially in memory, but data members across access specifiers may be reordered in memory.
class Foo {
public:
int a;
int b; // Must come after a
public:
int c; // Does not have to come after a and b.
};
The second public: gives more room for the optimizer.
There is no language purpose to doing that. I think it is bad style. But some people like to divide up everything of a particular kind into a section, and then divide the section into public/protected/private areas. Then when they don't happen to have anything but public elements, then the public keyword gets repeated redundantly.
I think its dumb. But some people find it useful to organize their code this way.

What are the advantages of declaring private members at the end of a class?

From http://sourcemaking.com/design_patterns/strategy/cpp/1:
class TestBed
{
public:
enum StrategyType
{
Dummy, Left, Right, Center
};
TestBed()
{
strategy_ = NULL;
}
void setStrategy(int type, int width);
void doIt();
private:
Strategy *strategy_;
};
Note how the private members have been declared at the end. I have seen this programming style at several other places, but somehow I find declaring private members first easier to read.
Are there any advantages of declaring private members at the end of the class, like done above?
When reading a class declaration the most important thing is the public interface and so it makes sense to go at the top. Your eyes shouldn't be drawn to the private members which hold the implementation.
It really doesn't matter much though. Pick a style (or be given one) and stick with it.
Actually, the only thing I can really think of it changing is the order of initialization of members. That seldom matters though.
Absolutely no, and I don't see why you should have benefits.
It's just a matter of personal taste, you should try to understand where your eyes prefer to look for them and stick that way.
In the original C++ implementation, all the members had to be declared at the beginning of a class, or code in the method definitions couldn't see them. The ability to define members at the end was added later, and some folks, relishing their new freedom, adopted this style and stuck with it. Either location makes sense, though.
Declaring private members at the end of a class is definitely a naming convention. Not required but easy to read since it's common to see them listed after public members.
However, you can also omit the "private:" part and just declare your private members outside of the public ones. If you do not put these variables under the "private:" part and just declare them outside (in this case, above) the "public:" area, they should automatically be defaulted to private.

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.