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?
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.
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.
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).
It is an object of type CRectangle that is global or belongs to a namespace depending on the context.
It declares an instance. Just like:
class CRectangle
{
// ...
};
CRectangle rect;
There is no difference between a class
and a struct
in C++, except struct
s default to public (in regards to access specifiers and inheritance)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With