jpm
jpm

Reputation: 1083

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.

Upvotes: 6

Views: 30330

Answers (2)

Kerrek SB
Kerrek SB

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

Some programmer dude
Some programmer dude

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

Related Questions