469,913 Members | 1,947 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,913 developers. It's quick & easy.

call static method when class initialized

I have a class

class MyClass
{
private:
static double a;
static void computeA(){
a =....;
}

public:
static double getA();
}

User uses my code like:

double x = MyClass::getA();

I want the method computeA() be called the first time MyClass is used,
just like the "static" in java. How can I do it?

Thanks,

Sep 14 '05 #1
2 4148

Ge Cong wrote:
I have a class

class MyClass
{
private:
static double a;
static void computeA(){
a =....;
}

public:
static double getA();
}

User uses my code like:

double x = MyClass::getA();

I want the method computeA() be called the first time MyClass is used,
just like the "static" in java. How can I do it?


I don't think there's a perfect equivalent. You can either initialize
the static data when you declare it:

double MyClass::a = MyClass::doComputeA();

or you can call the compute method in getA():

double MyClass::getA()
{
static bool init = false;
if( !init )
{
computeA();
init = true;
}
return a;
}

Cheers! --M

Sep 14 '05 #2
* Ge Cong:
I have a class

class MyClass
{
private:
static double a;
static void computeA(){
a =....;
}

public:
static double getA();
}
Semicolon.

Missing definition of 'a' (it's declared in the class, but you also need
a definition outside the class),

double MyClass::a = something();

User uses my code like:

double x = MyClass::getA();

I want the method computeA() be called the first time MyClass is used,
just like the "static" in java.
Generally it's not a good idea to want things to be like Java.

What you need technically is just that 'a' is initialized before it's used.

Btw., in my humble opinion novices should not be allowed to use 'static' in
Java -- it is a sure way to create a hopeless spaghetti system that is next
to impossible to test, extend, debug, ...

How can I do it?


Low-level approach: initialize 'a'. ;-)

Shown above.

Higher-level approach: redesign as a singleton.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Sep 14 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

11 posts views Thread by sks_cpp | last post: by
3 posts views Thread by Marcin Vorbrodt | last post: by
5 posts views Thread by Jim Langston | last post: by
8 posts views Thread by Robert A Riedel | last post: by
10 posts views Thread by John A Grandy | last post: by
10 posts views Thread by sunil | last post: by
1 post views Thread by Waqarahmed | last post: by
reply views Thread by Salome Sato | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.