1

What happens to a member variable in C++ if you don't define the access rights?

For instance, in the following code:

class Base {
  int myQuestion;
  public:
    int myPublic;
  private:
    int myPrivate;
}

Who has access to myQuestion?

Jonathan Lam
  • 16,831
  • 17
  • 68
  • 94
busssard
  • 11
  • 1

3 Answers3

5

If you use the keyword class, access defaults to private. If you use struct it defaults to public.

That's pretty much the only difference between the two keywords.

The only other difference is when you inherit, class defaults to private inheritance, struct to public inheritance.

Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70
  • It is the only difference – king_nak Aug 02 '16 at 12:15
  • [Both types are classes; C++ does not have structs](http://coliru.stacked-crooked.com/a/28a9cdb264a25723). Discuss use of the _keywords_ `class` and `struct` instead, to avoid spreading misconceptions. – Lightness Races in Orbit Aug 02 '16 at 12:16
  • @king_nak "It is the only difference" - you forget the difference in default inheritance. There are *two* differences between `class` and `struct`; default access and default inheritance type. – Jesper Juhl Aug 02 '16 at 15:24
1

In a class, it is private. In a struct, it is public.

king_nak
  • 11,313
  • 33
  • 58
1

In class it is private, in struct it is public by default.

Adrian Jałoszewski
  • 1,695
  • 3
  • 17
  • 33