nonalias
nonalias

Reputation: 11

Why does the address value of a member variable declared as an object in a class always change? in c++

I am studying about the class of c++. I am writing a class named User. The member variable was declared as an object in the class. The function that returns the address of this object is getAddr(). For your information, the getAddr() function also exists in the User class.

I found something strange while printing the address value of the user object and the person object in the user object. I found that the address value of the Person object in the User object changes every time I call getAddr().

The code I wrote is as follows.

#include <iostream>
#include <sstream>

class Person {
    private:
        int num;
    public:
        Person(){};
        std::string getAddr() {
            std::stringstream ss;
            ss << this;
            return (ss.str());
        }
};

class User {
    private:
        Person _person;
        Person *_ptr_person;
    public:
        User() {
            this->_ptr_person = new Person();
            this->_person = Person();
        }
        std::string getAddr() {
            std::stringstream ss;

            ss << this;
            return (ss.str());
        }
        Person *getPtrPerson() {
            return this->_ptr_person;
        }
        Person getPerson() {
            return this->_person;
        }
        ~User() {
            delete this->_ptr_person;
        }
};

void run()
{
    User a = User();

    // User address
    std::cout << a.getAddr() << std::endl;
    std::cout << a.getAddr() << std::endl;
    std::cout << a.getAddr() << std::endl;
    // doesn't changed
    std::cout << std::endl;
    
    // Person's address in User
    std::cout << a.getPerson().getAddr() << std::endl;
    std::cout << a.getPerson().getAddr() << std::endl;
    std::cout << a.getPerson().getAddr() << std::endl;
    // changed
    std::cout << std::endl;

    // Ptr Person's address in User
    std::cout << a.getPtrPerson()->getAddr() << std::endl;
    std::cout << a.getPtrPerson()->getAddr() << std::endl;
    std::cout << a.getPtrPerson()->getAddr() << std::endl;
    // doesn't changed
    std::cout << std::endl;

}

int main(void)
{
    run();
}

The output of this code is as follows:

enter image description here

If you look at the output in the middle three lines, you can see that the address value always changes.

However, if you declare a Person object as a pointer within a User object and generate it through dynamic assignment, the address value remains unchanged (the output of the three lines below).

Why is this happening?

The questions are as follows:

Upvotes: 1

Views: 488

Answers (1)

Gabend
Gabend

Reputation: 91

The address changes, because when you call a.getPerson() the person returned from the function is a copy of the original one that is a class member of User.

Upvotes: 6

Related Questions