Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

public

class

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?

like image 509
Abhineet Avatar asked Apr 27 '10 08:04

Abhineet


People also ask

Can you have multiple public/private protected areas inside a class C++?

There is no limit to how many of these access qualifiers(public, private, protected) you can have in a class.

Can derived classes access private members?

Private members can only be accessed by member functions of the same class or friends. This means derived classes can not access private members of the base class directly!

What is the difference between a class and a structure in C++?

The C++ class is an extension of the C language structure. Because the only difference between a structure and a class is that structure members have public access by default and class members have private access by default, you can use the keywords class or struct to define equivalent classes.

Is struct and class same?

The only difference between a struct and class in C++ is the default accessibility of member variables and methods. In a struct they are public; in a class they are private.


1 Answers

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.

like image 142
Marcelo Cantos Avatar answered Sep 20 '22 05:09

Marcelo Cantos