call static method when class initialized

G

Ge Cong

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,
 
M

mlimber

Ge said:
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
 
A

Alf P. Steinbach

* 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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,048
Latest member
verona

Latest Threads

Top