0

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 Answers4

2

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

It's the same as

class A { ... };

A r;

int main() { ... }
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
1

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;
Mark Garcia
  • 17,424
  • 4
  • 58
  • 94
0

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.

hetepeperfan
  • 4,292
  • 1
  • 29
  • 47
0

maybe this helps you for a better understanding.

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

br

Community
  • 1
  • 1
Paulquappe
  • 144
  • 2
  • 6
  • 15