What do you call this construct?

J

joe

Curious if this type of construct has a name, or is a recognized
design pattern:

class Function
{
public:
Function() { // do loads of work here in the Constructor, store result
in m_result }

operator double() { return m_result;} //Automatic Type Conversion

private:
double m_result;
};

with the expected simple usage:

double value = Function();

Is there some recognized caveat to the above? I don't see it used
very often.
 
V

Victor Bazarov

joe said:
Curious if this type of construct has a name, or is a recognized
design pattern:

class Function
{
public:
Function() { // do loads of work here in the Constructor, store result
in m_result }

operator double() { return m_result;} //Automatic Type Conversion

private:
double m_result;
};

with the expected simple usage:

double value = Function();

Is there some recognized caveat to the above? I don't see it used
very often.

What's the advantage of that class implementation over, say,

double Function() {
double _result;
// do loads of work here, store the result in _result
return _result;
}

? I don't see any in your code. And the syntax looks pretty much
like a function call, so it would be very confusing to somebody
reading the code to learn that 'Function' is not a function at all.

V
 
I

Ian Collins

joe said:
Curious if this type of construct has a name, or is a recognized
design pattern:

class Function
{
public:
Function() { // do loads of work here in the Constructor, store result
in m_result }

operator double() { return m_result;} //Automatic Type Conversion

private:
double m_result;
};

with the expected simple usage:

double value = Function();

Is there some recognized caveat to the above? I don't see it used
very often.
I guess it could be called the "abuse of a class" pattern.
 
V

Venkat

Without going into "it is a bad idea to do", I would refer you to
TCPL, 3rd Ed. S11.4.
It is a way to do type conversion.
 

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

No members online now.

Forum statistics

Threads
474,431
Messages
2,571,677
Members
48,796
Latest member
Greg L.

Latest Threads

Top