using same C++ access specifiers multiple times - c++

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.

Related

Should I make a class polymorphic if only one of its methods should behave differently depending on the object's data type?

I have a class Group containing a vector of objects of another class Entry. Inside the Group I need to frequently access the elements of this vector(either consequently and in random order). The Entry class can represent a data of two different types with the same properties(size, content, creation time etc.). So all of the members and methods of the Entry class are the same for both data types, except for one method, that should behave differently depending on the type of the data. It looks like this:
class Entry
{
public:
// ...
void someMethod();
// ...
private:
TYPE type_;
// ...
};
class Group
{
private:
// ...
std::vector<Entry> entries_;
// ...
};
void Entry::someMethod()
{
if (type_ == certainType)
{
// Do some stuff
}
else if (type_ == anotherType)
{
// Do some different stuff
}
}
Given the abilities of C++ regarding OOP, this approach seems unnatural to me. I am thinking about creation of two distinct classes inherited from the Entry class and overriding only this someMethod() in those classes:
class Entry
{
// ...
virtual void someMethod() = 0;
// ...
};
class EntryType1 : public Entry
{
// override someMethod() here
};
class EntryType2 : public Entry
{
// override someMethod() here
};
But doing so means reducing the efficiency of cache usage, because now inside the Group class I have to replace the vector of Entry objects placed in a contiguous memory area with the vector of pointers to Entry base class objects scattered all over the memory address space.
The question is - is it worth it to make a class polymorphic just because of one only among many other of its methods is needed to behave differently depending on the data type? Is there any better approach?
is it worth it to make a class polymorphic just because of one only among many other of its method is needed to behave differently depending on the data type?
Runtime polymorphism starts to provide undeniable net value when the class hierarchy is deep, or may grow arbitrarily in future. So, if this code is just used in the private implementation of a small library you're writing, start with what's more efficient if you have real reason to care about efficiency (type_ and if), then it's not much work to change it later anyway. If lots of client code may start to depend your choices here though, making it difficult to change later, and there's some prospect of further versions of someMethod() being needed, it's probably better to start with the virtual dispatch approach.
Is there any better approach?
Again - what's "better" takes shape at scale and depends on how the code is depended upon, updated etc.. Other possible approaches include using a std::variant<EntryType1, EntryType2>, or even a std::any object, function pointers....
If you are absolutely sure that there are only two types of Entry, then using an if inside the function's implementation is, to me, a perfectly valid approach. In this case, I would advise you to use if constexpr to further indicate that this is a compile-time behavioral decision and not a runtime one. (As pointed out by Tony Delroy, if constexpr is not viable).
If, however, you are unsure if you are going to need more Entry types in the future, the if approach would only hurt you in the long run. If you need the scalability, I would advise you to make the Entry class hold a std::function internally for only that specific behavior that needs polymorphism: this way you're only paying for indirection when you actually need the functionality.
You could also make two factory functions make_Entry1 and make_Entry2 that construct an Entry passing it the specific std::function that yields the desired behavior.

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.

Architecture of a director / executive / master / top-level application layer

I have a collection of classes and functions which can interact with one another in rich and complex manners. Now I am devising an architecture for the top-level layer coordinating the interaction of these objects; if this were a word processor (it is not), I am now working on the Document class.
How do you implement the top-level layer of your system?
These are some important requirements:
Stand-alone: this is the one thing that can stand on its own
Serializable: it can be stored into a file and restored from a file
Extensible: I anticipate adding new functionality to the system
These are the options I have considered:
The GOF Mediator Pattern used to define an object that encapsulates how a set of objects interact [...] promotes loose coupling by by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently.
The problem I see with mediator is that I would need to subclass every object from a base class capable of communicating with the Mediator. For example:
class Mediator;
class Colleague {
public:
Colleague(Mediator*);
virtual ~Colleague() = default;
virtual void Changed() {
m_mediator->ColleagueChanged(this);
}
private:
Mediator* m_mediator;
};
This alone makes me walk away from Mediator.
The brute force blob class where I simply define an object and all methods which I need on those objects.
class ApplicationBlob {
public:
ApplicationBlob() { }
SaveTo(const char*);
static ApplicationBlob ReadFrom(const char*);
void DoFoo();
void DoBar();
// other application methods
private:
ClassOne m_cone;
ClassTwo m_ctwo;
ClassThree m_cthree;
std::vector<ClassFour> m_cfours;
std::map<ClassFive, ClassSix> m_cfive_to_csix_map;
// other application variables
};
I am afraid of the Blob class because it seems that every time I need to add behaviour I will need to tag along more and more crap into it. But it may be good enough! I may be over-thinking this.
The complete separation of data and methods, where I isolate the state in a struc-like object (mostly public data) and add new functions taking a reference to such struct-like object. For example:
struct ApplicationBlob {
ClassOne cone;
ClassTwo ctwo;
ClassThree cthree;
std::vector<ClassFour> cfours;
std::map<ClassFive, ClassSix> cfive_to_csix_map;
};
ApplicationBlob Read(const char*);
void Save(const ApplicationBlob&);
void Foo(const ApplicationBlob&);
void Bar(ApplicationBlob&);
While this approach looks exactly like the blob-class defined above, it allows me to physically separate responsibilities without having to recompile the entire thing everytime I add something. It is along the lines (not exactly, but in the same vein) of what Herb Sutter suggests with regards to preferring non-member non-friends functions (of course, everyone is a friend of a struct!).
I am stumped --- I don't want a monolith class, but I feel that at some point or another I need to bring everything together (the whole state of a complex system) and I cannot think of the best way to do it.
Please advise from your own experience (i.e., please tell me how do you do it in your application), literature references, or open source projects from where I can take some inspiration.

In C++ can a class attributes - public,private or protected be set/changed at run-time?

Is it possible to change the class attribute at run-time in C++ language.For example as below :
class base
{
public:
//public members
private :
//private members
};
class derived1 : attribute base
{
public:
//public members
base::<base method name> //so that it an be made accessible from the main - outside the class.
private:
//private members
};
can the attribute-public,private,protected be changed at runtime, dynamically?
Rgds,
softy
It is the compiler that makes sure you don't access private members. Once the compiler finishes its work and the binary code is generated, all information regarding private-ness is lost.
So no, you can't change that in runtime.
I don't know why you would want this, but if you want some functions to be able to be called during some times, but not the others, you can have a variable defining whether they can be called or not. Then, on the top of that function:
int Class::function(...)
{
if (!function_is_allowed)
return OPERATION_NOT_ALLOWED;
...
}
No, the access level cannot be modified, although there are some hacks to go around them.
Refer to this answer - https://stackoverflow.com/a/6886432/673730
If what you're looking for is something similar to Java reflection, where you can access private members by modifying their access level at runtime, then no.
You cannot change the access modifiers of a class. End of story.
Disclaimer: There are hacks for just about everything, including this. Don't use them.
Based on your comments in the question when asked why you want this, it looks like what you're trying to do is control access to a class' run-time properties based on its other run-time properties. For example, maybe a Character's Powers are only accessible if Character's Level is >= 42.
This is not a technical question about the mechanics of C++ syntax, but a business logic question. You'll find the answer to this question in the design of your program and its algorithms -- not some technical C++ trick.
Classes are often used to model things. In your case, a character in a game. Maybe this character has a level and a list of powers (which I'll represent simply as strings).
In that case:
class Character
{
public:
int level_;
vector<string> powers_;
};
...is a simplistic representation of your character model. Now, if you want to control access to powers_ at run-time based on the value of level_, you can use an accessor method:
class Character
{
public:
int level_;
vector<string> Powers() const
{
if( level_ >= 42 )
return powers_;
else
return vector<string>();
}
private:
vector<string> powers_;
};
Now you can only get to the character's powers if the character is of sufficiently high level.
This is still a highly simplistic example, and the above code is not production quality. However, the idea is there -- when implementing your program's business logic, your focus should be on the algorithms you write much more than the technicalities of C++, or whatever language you're using.

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

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.