Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class declaration confusion - name between closing brace and semi-colon

Tags:

c++

c

oop

class

struct

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?

like image 288
Matthew H Avatar asked Mar 26 '10 21:03

Matthew H


People also ask

Do class declarations end with a semicolon do class method definitions?

If it's a definition, it needs a semicolon at the end. Classes, structs and unions are all information for the compiler, so need a trailing ; to mark no declared instances. If it contains code, it doesn't need a semicolon at the end.

Why use a semicolon at the end of a class?

A semicolon after a close brace is mandatory if this is the end of a declaration. In case of braces, they have used in declarations of class, enum, struct, and initialization syntax. At the end of each of these statements, we need to put a semicolon.


3 Answers

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).

like image 140
Tyler McHenry Avatar answered Oct 23 '22 03:10

Tyler McHenry


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

like image 33
Khaled Alshaya Avatar answered Oct 23 '22 04:10

Khaled Alshaya


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)

like image 42
GManNickG Avatar answered Oct 23 '22 05:10

GManNickG