6
class CRectangle {
    int x, y;
  public:
    void set_values (int,int);
    int area (void);
  } rect;

In this example, what does 'rect' after the closing brace and between the semi-colon mean in this class definition? I'm having trouble finding a clear explanation. Also: Whatever it is, can you do it for structs too?

Matthew H
  • 5,831
  • 8
  • 47
  • 82

4 Answers4

12

rect is the name of a variable (an object in this case).

It is exactly as if it had said:

  int rect;

except instead of int there is a definition of a new type, called a CRectangle. Usually, class types are declared separately and then used as

  CRectangle rect;

as you are probably familiar with, but it's perfectly legal to declare a new type as part of a declaration like that.

And yes, it works for structs:

  struct SRectangle { int x, y; } rect;

In fact you don't even have to give the type a name if you don't plan to use it again:

  struct { int x, y; } rect;

that's called an "anonymous struct" (and it also works for classes).

Tyler McHenry
  • 74,820
  • 18
  • 121
  • 166
  • 1
    It's an "unnamed struct", not an "anonymous struct". C++ does not have anonymous structs. See http://stackoverflow.com/questions/2253878/why-does-c-disallow-unnamed-structs-and-unions – Johannes Schaub - litb Mar 26 '10 at 21:47
2

It is an object of type CRectangle that is global or belongs to a namespace depending on the context.

Khaled Alshaya
  • 94,250
  • 39
  • 176
  • 234
1

It declares an instance. Just like:

class CRectangle
{
    // ...
};

CRectangle rect;

There is no difference between a class and a struct in C++, except structs default to public (in regards to access specifiers and inheritance)

GManNickG
  • 494,350
  • 52
  • 494
  • 543
1

The one and only difference between structs and classes is that structs have a public default inheritance and access and classes use private as default for both.

Edward Strange
  • 40,307
  • 7
  • 73
  • 125