Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

Not sure this is going to be easy to explain but ...

I have a class (A) that needs to have access to a map (mapCodes), this map is the same for all instances of class(A), therefore I don't want to create an instance of the map for each instance of class A and populate it, etc ....

 

This is my code right now:

 

A.h (header file)


class A
{
private:
static map<int, string> mapCodes;

public:
A(); // constructor
};
[/Code]

 

A.cpp (header file)

[Code]
A::A
{
mapCodes[1] = "AAA";
mapCodes[2] = "BBB";
mapCodes[3] = "CCC";

}
[/Code]

 

Now, for every object of class A I call the constructor which uses the same STATIC mapCodes (which is good) but the constructor also repopulates it each time ... what a waste ...

Isn't there a way I can ... declare mapCodes and its initialization as static so I only have 1 instance populated once?

 

I was looking into doing something like using a STATIC CLASS or STATIC STRUCT but couldn't seem to get it to work - when doing some reading a lot of people were saying that c++ doesn't really support STATIC CLASSES...

 

Any help would be much appreciated...

Thanks,

  • Administrators
Posted
You could declare the constructor as static and it would only be run once, however static constructors get execute before any of your application's code - this can cause startup performance issues if this initialisation is slow / memory hungry.

Posting Guidelines FAQ Post Formatting

 

Intellectuals solve problems; geniuses prevent them.

-- Albert Einstein

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...