Omkar
Omkar

Reputation: 831

Why i can't assign a returned reference to a pointer directly?

I have declared geta() function to return a reference to a,which i have to collect in an int pointer. The code is working fine,but why i could not use the commented line. Isn't it doing the same thing? The code is as follows:

#include<iostream>
using namespace std;
class Foo
{
    int a=6;
public:
    int& geta()
    {
        return a;
    }
};
int main()
{
    Foo f;
    int &z = f.geta();          //int *p = f.geta();  Why this doesn't work?
    int *p = &z;
    cout << *p;
}

Upvotes: 0

Views: 3440

Answers (4)

M-J
M-J

Reputation: 1103

Good answers are here already, so I borrow some of their good sentences and try to provide you with a more plain simple answer.

Keep in mind that a pointer is an address of the computer memory, and when it comes with an asterisk sign, it may mean doing two different things: 1_definition, 2_dereferencing.

The notable thing here is that you can do initializing on the same line that you're defining the pointer, or on separate lines. So these two are equivalents:

int x=8;
int *ptr=&x; //this is equivalent for
//this:
int *ptr;
ptr=&x;

Nearly same two tasks are done with ampersand sign(defenition and referencing). You can:

1_define references, however, here's a subtle special rule to note, you can't define references in one line and reference them in another. In other words, you must initialize a reference with another variable whenever you define it. and from that moment on, it becomes an alias for it! e.g. if it's being referenced to an int, it acts really like that int!(just like in your case), the only difference is that it will have the address of that int too, somewhere behind the scenes.

(Even once you make a reference to an object, it cannot be changed to refer to any other objects later.)

2_The other thing that ampersand sign does is (as Monirul Islam Milon said in another answer) the extraction of the address of a variable.

Now after those basic stuff, you're ready to take a look at this(better if you run it too):

int main()
{
    int j=25;
    int* ptr;
    ptr = &j;
    int& ref1 = j, ref2 = *ptr;
    //-------int& ref3 = ptr; // <-------- error!
    //-------You can not assign an address to an int!
    //-------Remember that in the valid examples above, ref1 and ref2 are really nothing but j
    cout << "j is: " << j << endl;
    cout << "ref1 is: "<< ref1 << '\t' << "ref2 is: " << ref2 << endl;
    cout << "They are both aliases for j";

In pass-by-reference functions, the same thing happens, objects themselves are sent to those functions, held in aliases(alternate names) though, as parameters. Also please note that, in return-by-reference functions, you're not returning an address, rather you're returning the object itself--whatever it is-- through its alias(through the reference to it). So:

class_name& foo2(){
static class_name x=something;
return x;
} //OK
//but:
//-------int *ptr2 = foo2(); // <-------error!

Again in the last line, you're trying to assign a class(e.g.int,float,a user-defined one,etc...) to a pointer, which is obviously not valid(based on the most basic rules of C++).

I have used these links to write this answer for you: link, link, link, link.

I hope it helps.

Upvotes: 0

dj1986
dj1986

Reputation: 362

 using namespace std;
class Foo
{

public:
    int a;
    int& geta()
    {
        return a;
    }
};
int main()
{
    Foo f;
    f.a = 6;
    int &z = f.geta(); //int *p = f.geta();  Why this doesn't work?
    z = 10;   // 'z' is nothing but 'a'
    int *p = &z;
    cout << *p;
}

you can see in above z is nothing but a. both are pointing to same memory. and int *p is a pointer which will contain the address. so either you can p = &z; or *p = z;

int *p = f.geta(); means you are assigning a reference to pointer variable means address of a to *p which is not valid. when p = &a or p = &z means assign address of a / z to p which on de-referencing will give you the value. pointer

Upvotes: 0

mystic_coder
mystic_coder

Reputation: 472

Well, You cannot assing pointer to int : Rather you can allocate new memory for pointer and assing value to it like below code :

#include <iostream>
#include <string>

using namespace std;
class Foo
{
    int a;
public:
    Foo():a(6) {}
    int& geta()
    {
        return a;
    }
};
int main()
{
    Foo f;
    int *p = new int;
    *p = f.geta();
    //int *p = &z;
    cout << *p;
}

Upvotes: 0

Md. Monirul Islam
Md. Monirul Islam

Reputation: 731

Don't get confused with & and * symbol. The meaning of symbol & is different in an expression and in a declaration.

When it is used in an expression, & denotes the address-of operator, which returns the address of a variable.

However, when & is used in a declaration (including function formal parameters), it is part of the type identifier and is used to declare a reference variable (alias/ alternate name).

Reference and Pointer are not the same thing. You can check here... What are the differences between a pointer variable and a reference variable in C++?

Upvotes: 6

Related Questions