Moe
Moe

Reputation: 1051

Use a function return value directly as reference in c++

Recently I have to use C++ for a course at university. I'm aware of the concept of pointers and references, but i'm humbling at a specific point.

consider following class definition:

class test{
    public:
        test(int i);
        ~test();
        int* getint();
    private:
        int *asdf;
};

test::test(int i){
     asdf = new int();
    *asdf = i;
}

int* test::getint(){
    return asdf;
}

and the following code:

void fun1(int*& i){
    *i +=1;
}

int main(){
    test *a = new test(1);
    fun1(a->getint());
}

If i'm compiling it with g++ i'll get an error message:

error: invalid initialization of non-const reference of type ‘int*&’ from an rvalue of type ‘int*’

I see where the problem is, and that it can be solved by declaring a new pointer like this:

int main(){
    test *a = new test(1);
    int* b = a->getint();
    fun1(b);
}

But is there any other way to use the return value directly as a reference? If my C++ code is terrible, you're welcome to correct it (it's basicly my first week of C++).

EDIT: changed fun1 to use reference and corrected initilization of class variable (as suggested by enrico.bacis

Upvotes: 1

Views: 160

Answers (2)

CashCow
CashCow

Reputation: 31435

There are several issues, as in C++ you have to manage memory properly and cannot just call new all the time without taking care of deletion later.

I think this

void fun1(int* i)
{
  *i +=1;
} 

will give the +=1 a higher operator precedence than the * so you need to do:

void fun1(int* i)
{
  (*i) +=1;
} 

Note that the function needs to take int* as a parameter not int *&. You would only take int *& if you want to modify the pointer itself, rather than what it points to. And in such a case you could not pass in the return value of getint() which appears to be giving you your compiler error.

Upvotes: 1

enrico.bacis
enrico.bacis

Reputation: 31484

You are defining a new asdf variable in the constructor of the class test that shadows the instance variable.

Change the line:

int* asdf = new int();

with:

asdf = new int();

Upvotes: 3

Related Questions