Can in this way be declared a global object class?

92 views Asked by At

I do not know why but this code works, what does this record }r; and how it works ? can in this way be declared a global object class ?

#include <iostream>

class А
{
    public:
        А()
        {
            std::cout << "Hello World";
        }
}r;

int main()
{

}
4

There are 4 answers

0
Some programmer dude On BEST ANSWER

That declares a global variable named r that is of type A.

It's the same as

class A { ... };

A r;

int main() { ... }
0
hetepeperfan On

It Create one instance of class A with name r. It's pretty much the same as doint int r; Which would make a global int on that position.

0
Mark Garcia On

can in this way be declared a global object class ?

Um, yeah! Basically, r there is a global variable of type А. C++ has inherited from C a certain syntax that enables you to declare variables after a class/struct definition. You can often see from C something like

struct vertex {
   float x, y;
} my_vertex; // Declares a variable of type vertex

In C++, a struct is the same as class with the exception of the default access specifier.

You might have wondered what the semicolon is for after class definitions. So basically a class defined as

class my_class {};

with the braces immediately proceeded by a semicolon declares no variables.

You can also declare more than one variables by delimiting them with the comma operator.

class my_class {} x, y, z;
0
Paulquappe On

maybe this helps you for a better understanding.

C++: Declare a global class and access it from other classes?

br