I\'m working on a project for class and I\'m using classes and pointers of type class to call some functions in the class but it\'s crashing on Code Blocks and Eclipse and I don
a *Ptr; Ptr->set_X(5);
Your Ptr
does not point to anything. Trying to invoke a member function on an uninitialised pointer results in undefined behaviour. Crashing is just one of the many more or less random things that can happen.
Luckily, in your example, you do not need a pointer anyway. You can simply write:
a my_a;
my_a.set_X(5);
Pointers often point to dynamically allocated objects. If this is what you want, you must use new
and delete
accordingly:
a *Ptr = new a;
Ptr->set_X(5);
delete Ptr;
In modern C++, std::unique_ptr
is typically a superior alternative because you don't have to manually release the allocated memory, which removes a lot of potential programming errors:
auto Ptr = std::make_unique();
Ptr->set_X(5);
// no delete necessary