Sign in to follow this  

Initializing Static Object Member (Constructor)

This topic is 2425 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

In a class, when you declare a variable of type "static," you must initialize it before use. Say, for instance, that the particular variable is an instance of another class though. How would you initialize statically?

So far, I've noticed that when you create a static array of objects, that their constructors are automatically called.

Example:
[code]
class A
{
private:
static MyObject obj[];
};

MyObject A::obj[1]; // creates 1 instance of MyObject and calls its constructor
[/code]

Is there another way to do this without arrays?

Share this post


Link to post
Share on other sites
Like this:

[code]class A
{
private:
static MyObject obj;
};

MyObject A::obj(arg1, arg2, arg3);

// or if you don't need arguments for constructor:
// MyObject A::obj;
[/code]

Share this post


Link to post
Share on other sites
[quote name='Master Jake' timestamp='1306638357' post='4816973']
In a class, when you declare a variable of type "static," you must initialize it before use.
[/quote]
This is of course true with any variable, not just statics, of course.

[quote]
Say, for instance, that the particular variable is an instance of another class though. How would you initialize statically?
[/quote]

[code]
#include <string>
#include <iostream>

struct A { static std::string messages[3]; };

std::string A::messages[3] = {
std::string("hello"), // Don't really need to explicitly call string
std::string("goodbye"), // ctor here, could use conversion from const char*.
std::string("thanks for all the fish") // For illustration purposes.
};

int main()
{
for (int i = 0; i != sizeof A::messages / sizeof *A::messages; ++i)
std::cout << A::messages[i] << '\n';

return 0;
}
[/code]

[quote]
So far, I've noticed that when you create a static array of objects, that their constructors are automatically called.
[/quote]
They have to be initialized somehow and the point of constructors is to initialize, so this seems entirely reasonable :)

[quote]
Is there another way to do this without arrays?
[/quote]

Do [i]what[/i] without arrays?

Share this post


Link to post
Share on other sites
[quote name='MartinsM' timestamp='1306661442' post='4817032']
Like this:

[code]class A
{
private:
static MyObject obj;
};

MyObject A::obj(arg1, arg2, arg3);

// or if you don't need arguments for constructor:
// MyObject A::obj;
[/code]
[/quote]

Thank you very much! It seems so obvious now that I feel somewhat stupid.

Thanks for your reply too edd, but Martin's example pretty much takes care of what I want to do.

Share this post


Link to post
Share on other sites
Sign in to follow this