1

I am a C++ beginner and I understand basic idea of call by reference or value. But in the following case, I got confused whether this call by reference or value. I am reading other people's code, and I simplified it by cutting other logic, just keep the logic which shows whether it call by reference or value.

Here is the code

class Profile
{
public:
    int test = 1;
    Profile() {}
    Profile(const Profile& original)  // create a reference original and then assign the object (*aProfile) to it
    {
        *this = original;
    }
    void change() 
    {
        test = 2; 
    }
};

class Asset
{
public:
    Profile theProfile;
    Asset() {}
    Asset(Profile *aProfile)  // aProfile should be a pointer points to Profile
    {
        theProfile = Profile(*aProfile); // create another object by (*aProfile)
        theProfile.change();
    }
};


int main() {
    Profile test; // create the object test
    Asset a(&test); // take the address of test as argument
}

And my question is why the a.theProfile is not the same as the test? From my understanding theProfile is the reference of the (*aProflie) and aProfile is pointer points to test object, which means they share one same address. If test in this address changed, why didn't test.test change to 2?

Could anyone help me to understand this? thanks!

Happy Bing
  • 11
  • 4
  • 2
    "_From my understanding theProfile is the reference_" Why? It is declared as `Profile theProfile;`, hence - it's not a reference. If it were declared as a `Profile& theProfile;` - it would be a reference. – Algirdas Preidžius Feb 04 '20 at 22:53
  • For the first question: Does this answer your question? [\*this vs this in C++](https://stackoverflow.com/questions/2750316/this-vs-this-in-c) – walnut Feb 04 '20 at 22:55
  • Please don't ask multiple unrelated questions at once. You can create multiple question posts instead. – walnut Feb 04 '20 at 22:56
  • @AlgirdasPreidžius, got it, thanks – Happy Bing Feb 04 '20 at 23:01
  • @walnut yes, it answers my first question. Thanks. – Happy Bing Feb 04 '20 at 23:10
  • Maybe you misunderstand the assignment operator, it means that the object on the right-hand side has its content copied to the object on the left hand side (it does not somehow cause the two different objects to become the same) – M.M Feb 04 '20 at 23:37
  • `my question is why the a.theProfile is not the same as the test?` because you copy the profile object in the call. – Taekahn Feb 05 '20 at 03:42

1 Answers1

0

this is a pointer to the calling object. So, in order to assign to the object, the this pointer has to be de-referenced. The Asset constructor takes a Profile pointer by value, and when it is de-referenced to be passed to the Profile constructor, that object that was being pointed to is passed by reference.

sweenish
  • 4,793
  • 3
  • 12
  • 23