Weird behavior with OOP and string pointers

The fix is simple and is to completely remove all pointers; see the code below. There are a number of issues with your code that I could address in detail, including memory leaks, uninitialized variables, and general misuse of pointers, but it seems that you’re possibly coming from a different language background and should spend time learning good practice and the important semantics and idioms in modern C++ from a good C++ book.

#include <iostream>
#include <string>

class Human
{
public:
    std::string name;
    void introduce();
};

void Human::introduce()
{
    std::cout << "Hello, my name is " << name << std::endl;
}

int main()
{
    Human martha;
    martha.name = "Martha";
    martha.introduce();

    return 0;
}

Leave a Comment