tags:

views:

89

answers:

5
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?

+2  A: 

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

AraK
or a class or a local scope.
KennyTM
+1  A: 

Yes, it'll work with structs too.

Ed
+8  A: 

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
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
+1  A: 

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)

GMan
+1  A: 

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.

Noah Roberts