0

I was trying to understand how a objects are stored in memory (heap) and how reference variable works. I wrote a simple program to understand the concept. But Why I am getting dereferenced address i.e. *(&cat) but not the &cat when function callBar() returns the address?

#include<iostream>
using std::cout;
using std::string;
class Cat{
        public: string name;
};
Cat* callBar(Cat *cat){
        cat = new Cat();
        cout<<&cat<<"\n";
        cout<<*(&cat)<<"\n";
            
        return cat;
}
int main(void){
        Cat *c = new Cat();
        cout<<&c<<"\n";
        cout<<callBar(c)<<"\n";
        cout<<*(&c)<<"\n";
        return 0;
}

The output of the code is:

0x7ffd38985d70
0x7ffd38985d48
0x56368fbd22b0
0x56368fbd22b0
0x56368fbd1e70

I created the instance of the class in the main and printed its address. I passed this object to another function and then printed its address again, which gave me new reference. Atlast, I deferenced it.

It is still not clear to me why I am getting dereferenced address i.e. *(&cat) but not the &cat when function returns?

1
  • There are no object references in the code provided. Maybe the question should be: How does object pointers work in c++? Commented Jul 12, 2020 at 14:46

1 Answer 1

2

It is still not clear to me why I am getting dereferenced address i.e. *(&cat) but not the &cat when function returns?

Inside callBar the relevant bits are...

Cat* callBar(...unused argument...){
    cat = new Cat();
    cout << &cat << "\n";
    cout << *(&cat) << "\n";
    return cat;
}

You're not getting &cat back because your return statement is return cat; not return &cat;.

But - the rest of your question - why are you getting *(&cat)? The & operator there takes the address of the Cat* cat local variable, then dereferences it with *: those operations cancel out, so *(&cat) == cat.

Sign up to request clarification or add additional context in comments.

3 Comments

How does it returns unchanged? I mean I am creating a new object on the same reference variable cat. cat = new Cat(); And If it cancel out then the addresses should match?
@SauravJaiswal • You are creating a new object on the same callBar local parameter variable cat. That has the effect of setting cat to a different value, not of changing the caller's c argument.
Sorry - I didn't even notice that line in the function - too sleepy! :-/ Point still stands though - after you assign that value to cat, *(&cat) is the same thing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.