Click here to Skip to main content
15,893,487 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C++
#include <stdio.h>
#include<iostream>
#include<cstring>
using namespace std;
class Base
{
    public:
        int a;
        Base():a(0){};
        Base(int x):a(x){};
        void geta(){
            cout<<"a="<<a<<endl;
        }
};
int main()
{
    Base b1(5);
    Base *b3 = &b1;
    Base &b2 = *b3;   //Is it okay?
    b2.geta();
    b3->geta();
    Base b4(10);
    b3 =  &b4;
    b2.geta();
    b3->geta();   
    return 0;
}


What I have tried:

The above Code compiles and gives desired output.
Output:
a=5
a=5
a=5
a=10
My questions:
1. Can we initialize a reference variable with a pointer variable?
2. If initializing of reference variable with pointer is allowed then when printing b2.geta(); and
b3->geta(); for the second time then both should have given the same value. Why they are different?
Posted
Updated 11-Oct-18 13:19pm

1 solution

Your question asks :
Quote:
Can we initialize a reference variable with a pointer variable?

Yes we can: your code demonstrates that.
The next thing is "
Quote:
both should have given the same value. Why they are different?


The output is correct. This is actually why we use pointers. Pointers - C++ Tutorials[^]
int main()
{
	Base b1(5);
	Base *b3 = &b1;   // Create pointer b3 and set to point to b1 b3->a==5
	Base &b2 = *b3;   // Create reference b2 and inititialize to whatever b3 points to which is b1 
	// NOTE at this line *b3 dereferences b3 which results in b1. If b3 did not point to a valid object (eg b3==NULL) this would cause the next line to fail at runtime

	b2.geta();
	b3->geta();

	Base b4(10);
	b3 = &b4;         // Now point b3 to b4 b3->a == 10
	cout << "a=" << b3->a << endl;
	b2.geta();
	b3->geta();
	return 0;
}


You set the pointer b3 to point to b1 but later you set it to point to b4. Thus the output is correct.
You can view what happens using your debubugger.
 
Share this answer
 
v2
Comments
CPallini 12-Oct-18 3:24am    
5.
GeekyMukesh 14-Oct-18 0:59am    
Thanks pwasser, for the reply and detailed explanation.
Just wanted to add a information that we should avoid assigning null pointer to reference like below:

int *p=0;
int &q = *p;

This code will compile but the result will be very unexpected, may be segmentation fault.
[no name] 14-Oct-18 3:46am    
Thanks for comment. However your point is already mentioned:
Quote: // NOTE at this line *b3 dereferences b3 which results in b1. If b3 did not point to a valid object (eg b3==NULL) this would cause the next line to fail at runtime

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900