return a pointer from a class method

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;
}


Try:
static double mymethod()

then
double(*myclass)() = &mymethod::myclass;
Last edited on
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
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?
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.
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
Topic archived. No new replies allowed.