return a pointer from a class method

Aug 1, 2011 at 10:14pm
hi, I have a class 'Myclass' and a method of that class 'Mymethod' which returns a pointer. I am not sure how to write that method. Can someone please help me ?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Myclass
{
public:
int n,m;
double *Mymethod()
}

double* Myclass::Mymethod()// Is this a correct way ?
{
do something;
return some address;
}

Aug 1, 2011 at 10:28pm

Try:
static double mymethod()

then
double(*myclass)() = &mymethod::myclass;
Last edited on Aug 1, 2011 at 10:29pm
Aug 1, 2011 at 10:33pm
closed account (zb0S216C)
Generally, when you return a pointer to something from a function, you're actually returning the address of the object you're returning. To return the address of something (through a pointer), you would write:

1
2
3
4
5
6
double Member;

double *Simple_function( void )
{
    return &Member;
}

You can change this function in two ways:
- Add a const qualifier before the return type-specifier (disallow modification of the returned value)
- Add a const qualifier after the parameter list (the function is not allowed to modify class members)

These two protect the returned value/members from modification.
Wazzak
Last edited on Aug 3, 2011 at 10:33am
Aug 2, 2011 at 10:41pm
I did not really understand as I am a beginner and trying object oriented programming for the first time.

I want to know whether 'double *Myclass::Mymethod()' is this a correct way to write a function of the class which returns an address?
Aug 2, 2011 at 11:11pm
double *MyClass::Mymethod();

is a method return the address of a double (returning a pointer to a double). So, yes, it is correct.

But it also be written as

double* MyClass::Mymethod();

or even

double * MyClass::Mymethod();

the first two are more common.

If your course text prefers one style, I would follow it. But beware that other people might use a different style.
Aug 2, 2011 at 11:16pm
Note that returning a pointer (or reference) to a built in type, like a double or int, is not normally done. These type are usually returned by value, e.g.

double MyClass::Mymethod();

It is larger data types, like structs, strings, and component classes that are turned by pointer or, preferably, by reference.

As you read on, pay special attention to mention of "const correctness", which Framework referred to above.
Last edited on Aug 12, 2011 at 3:46pm
Topic archived. No new replies allowed.