Home > Software design >  Question about Objects and Pointers in C
Question about Objects and Pointers in C

Time:09-14

#include <iostream>

struct Human {
public:
    std::string Name; 
    int* Age;
    Human(std::string Name, int Age): Name{Name}, Age{&Age} {}
    void Print() {
        std::cout << Name << " " << Age << "\n";
    }
};

int main() {
    Human a = Human("John", 35);
    Human b = Human("Brook", 20);
    Human c = Human("Lamy", 90);
    Human d = Human("Ed", 5);
    a.Print();
    b.Print();
    c.Print();
    d.Print();
}

/* Output
John 0x7bfc80
Brook 0x7bfc80
Lamy 0x7bfc80
Ed 0x7bfc80
*/

How come all the age value addresses are the same in the ouput? How am I able to send a constant value into something that will take its address? (check parameterized constructor) A constant has no well defined position in memory so how is that acceptable? Is the variable int* Age not being duplicated for each object creation?

Thank you!

CodePudding user response:

The addresses are those of the constructor argument. Your constructor is

Human(std::string Name, int Age): Name{Name}, Age{&Age} {}

That means: Name and Age are passed by value, a copy of the parameters is made. You then store the adress of this argument in the member. This doesnt make much sense. Age is local to the constuctor. Its lifetime ends when the constructor returns. What you store in the member is a dangling pointer. This is an example of pointless use of pointers. Make the Age member an int.

Note that if you would print the value the member is pointing to std::cout << *Age; in the Print method, your program would invoke undefined behavior, because the int to which the pointer points has its lifetime ended when the constructor returns.

CodePudding user response:

I saw a tiny mistake in your code. The two line:

    int* Age;
    Human(std::string Name, int Age): Name{Name}, Age{&Age} {}

has to be changed to:

    int Age;
    Human(std::string Name, int Age): Name{Name}, Age{Age} {}
  • Related