Reputation: 1083
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.
Upvotes: 6
Views: 30330
Reputation: 477010
It's certainly possible to have global objects. The correct way in your case is:
Foo foo(1, 3);
int main()
{
// ...
}
Upvotes: 5
Reputation: 409166
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.
Upvotes: 7