I am working on a program but can’t understand working with pointers when classes are involved. I know I have to allocate memory for the pointer using new and am fine with this when not using classes. I can’t find a simple tutorial to explain how to do this particular task though. Could someone please give me some help? This is the relevant snippets what I have done so far but it is outputting random characters:
"Hangman.c"
{
class Hangman
{
public:
...
char* remainingLetters();
Hangman()
{
char* remaining=new char[26];
}
~Hangman();
private:
char* remaining;
}
"Hangman.cpp"
{
...
char* Hangman::remainingLetters()
{
...does task to find remaining letters;
return remaining;
}
ostream& operator<< (ostream &out, Hangman &game)
{
out << "Letters remaining are: " << game.remaining <<endl
return out;
}
}
"main.cpp"
{
...
cout << game;
...
}
You’re not initializing you member. You should have:
Your version:
initializes a local variable called
remaining, whose scope is the constructor.Also you should
delete[]the memory in the destructor and implement the copy constructor and assignment operator.