Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using same C++ access specifiers multiple times

Tags:

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.,

};
like image 376
Zzz Zz Avatar asked Sep 11 '25 14:09

Zzz Zz


2 Answers

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.

like image 131
Jack V. Avatar answered Sep 14 '25 05:09

Jack V.


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).

like image 37
Frerich Raabe Avatar answered Sep 14 '25 04:09

Frerich Raabe