adohertyd
adohertyd

Reputation: 2689

Allocate memory for a pointer in a class constructor

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;
...
}

Upvotes: 0

Views: 2724

Answers (5)

Andreas Pflug
Andreas Pflug

Reputation: 11

One side aspect is that by doing

remaining=new char[26];

you are reserving space for 25 letters (+ one 0-byte), which is probably not what you want...

Regards

Andreas

Upvotes: 1

Bo Persson
Bo Persson

Reputation: 92261

Most of the problems go away if you use a C++ string instead of a C style array of char.

class Hangman 
{ 
public:
    std::string remainingLetters(); 

    Hangman()  { } 

private:
    std::string   remaining; 
};

"Hangman.cpp"

std::string Hangman::remainingLetters() 
{
    //  ...does task to find remaining letters;
   return remaining;  
} 

Upvotes: 3

Luchian Grigore
Luchian Grigore

Reputation: 258578

You're not initializing you member. You should have:

Hangman()
{
   remaining=new char[26];
}

Your version:

 Hangman()
 {
    char* remaining=new char[26];
 }

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.

Upvotes: 5

Alok Save
Alok Save

Reputation: 206518

Few important points:

  • You need to allocate memory using new [] to the pointer member in the constructor.
  • You need to deallocate the memory using delete [] in the destructor.
  • You need to follow the Rule of Three.

Also, note that creating a local pointer in the constructor with same name as your class member remaining is at best ambigiuos and you should rename it appropriately.

Upvotes: 1

Mahesh
Mahesh

Reputation: 34625

Hangman()
{
  char* remaining=new char[26];
}

In the constructor, you are initializing a local variable but not the class member. Also, every new/new[] should be associated with delete/delete[] respectively to avoid memory leaks. In stead of managing memory yourself, use smart pointers instead.

Upvotes: 2

Related Questions