Search code examples
c++classpointerspointer-to-member

Passing a number into member function causes program crash


I just started learning about pointers and how they can work as member functions. I started playing around a bit and eventually wrote this small bit of code:

class Animal
{
private:
    int *itsAge = 0;
    int *itsWeight = 0;

public:
    void SetAge(int age) { *itsAge = age; };
    int GetAge() { return *itsAge; };
};



int main() {

    Animal Lion;
    Lion.SetAge(3);
    cout << Lion.GetAge();

    return 0;

};

my question is why is my program crashing when I run it? In my mind I'm passing in the number 3 by value to the SetAge() function. Then, the copy of value 3 is stored in age which is then assigned to the value of the pointer itsAge. Is it because itsAge was never assigned an address? If so, does that mean initializing itsAge to 0, doesn't really prepare the pointer to be used?


Solution

  • Rewrite your program as:

    struct Animal {
        int age = 0;
        int weight = 0;
    };
    
    int main() {
        Animal lion;
        lion.age = 3;
        std::cout << lion.age;
        return 0;
    };
    

    No need for pointers. FYI your program is crashing because you are initializing those pointers to 0 and then derefencing them with *, which is Undefined Bevahiour.