Why are there multiple "public" keywords in header file?
Asked Answered
E

1

6

I am a new coder so forgive me for asking what maybe a very simple question. I am looking at some sample code on a method I am seeking to implement and I see the header seen below (first block of code).

class CIndividual  
{

public:
    CIndividual();
    virtual ~CIndividual();

public:
         vector<int> profit;
       vector<int> weight;    

public:
    CRandomNumber Rnd;
    bool dominated;
};

Why is public used multiple times? I am extremely confused by this coding structure and hope that this question is not too basic.

Ebberta answered 12/7, 2019 at 3:29 Comment(6)
They are redundant. The first one is quite sufficient. It's unclear why the author added the others; it's not common practice.Francoisefrancolin
Possible duplicate of Can there be two public section in a class? If yes then why ? And in which circumstances we do so?Selfconscious
The only time multiple public declarations are relevant is with toolkits like Qt where you could see public slots: in addition to just public:.Uncinus
perhaps some of them used to say private or protected, but a sloppy maintainer just changed it to public rather than remove it. Whichever way there should ideally just be one public statement.Kishke
Could be for "readability purposes or how variables or functions are divided for certain purposes. Maybe public: // mem. variables to store something specific. // private: // some functions used internally, public: // some static functions that can be used, or something like that. But ideally should be one public: and maybe multiple comment lines like // declaring mem. variables for.... // declaring functions for ... Or maybe like for public: // for this class, and public: // for inherited functions that were pure virtual and need to be implemented, etc.Apportion
On the other hand there should be a need for a virtual destructor, doesn't seem to inherit from anything..Apportion
C
8

In the case above, only 1 is enough, the first one. All the others are redundant. Some people prefer to rewrite these keywords to explicitly "separate blocks" of methods and member variables, but there's no real need in this case. Just matter of preference.

class MyClass
{
public:
  void myPublicMethod1();
  void myPublicMethod2();

private:
  myPrivateMethod();

private:                         // redundant, just group variables
  int somePrivateVariable;       // the first "private" should be enough as well
  string anotherPrivateVariable;

public:                          // not redundant here, but the variables
  int publicMember1;             // could be moved to the first group, if desired.
  bool publicMember2;
};
Coh answered 12/7, 2019 at 3:37 Comment(1)
Awesome! Thank you so much!Ebberta

© 2022 - 2024 — McMap. All rights reserved.