Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I declare class object globally in c++?

class Foo {
public:
    Foo(int a, int b);
        Foo();
};


Foo foo;
int main(){
 foo(1,3);
}

Is this the correct thing to do, if I am using a global class Foo?

If no, can you please which is the correct way to doing this?

NOTE: I want the class object globally.

like image 966
jpm Avatar asked Sep 16 '13 08:09

jpm


Video Answer


2 Answers

Yes, you can declare a global variable of any type, class or not.

No, you can't then "call" the constructor again inside a function to initialize it. You can however use the copy assignment operator to do it:

Foo foo;

int main()
{
    foo = Foo(1, 3);
}

Or you can have a "setter" function that is used to set or reinitialize the object.

By the way, and depending on the data in the class, you might want to read about the rule of three.

like image 131
Some programmer dude Avatar answered Oct 19 '22 08:10

Some programmer dude


It's certainly possible to have global objects. The correct way in your case is:

Foo foo(1, 3);

int main()
{
    // ...
}
like image 38
Kerrek SB Avatar answered Oct 19 '22 09:10

Kerrek SB