Class functions question

Started by
3 comments, last by paulcoz 23 years, 1 month ago
class AllocSomeMem { AllocSomeMem(); // default constructor ~AllocSomeMem(); // destructor char* buffer; // A pointer to our memory } AllocSomeMem::AllocSomeMem() { buffer = new char[1000]; // Allocate an array of 1000 chars } AllocSomeMem::~AllocSomeMem() { delete buffer; // If we have memory here, deallocate it } This is an example I found on this forum for constructors and deconstructors - they are not actually INSIDE the class definition. Are constructors/deconstructors (or any other member function for that matter) normally written outside or inside a class? I thought they had to be inside. Thanks, Paulcoz. Edited by - paulcoz on March 14, 2001 9:09:35 PM
Advertisement
The destructor should be "delete[] buffer" instead. The constructors and destructors should not be in the header file. For more info on this, read Meyers book (Effective C++).
The mistake with the [] was corrected in the other post too.

Aside from including the class in its own header/cpp file, do the constructors/destructors and other member functions belong within the class itself:

class jump
{
public:

int data;

jump::jump()
{
data = 0;
}
};

or outside:

class jump
{
public:
int data;

jump();
};

jump::jump()
{
data = 0;
}

Which way is correct? What is the difference if you can use both?

Paulcoz.
The functions become "inlined" when you declare it in class definition. It is generally not recommeneded to "inline" a function unless they are very small, like the one in your example. Note that when you define functions in header files, whenever the function definition is modified all the files depending on the header file will have to be re-compiled.
Some compiliers won't allow you to have certain things inlined like that. You can put it there but after a compile it will say something like "This function won't be written as inlined".
Things like loops, and switchs generally shouldn't be in the header.

If the function is only a couple of lines long and does some trivial stuff then inline it. Things like accessors and mutators.




-------
Andrew

Edited by - acraig on March 14, 2001 11:22:30 PM

This topic is closed to new replies.

Advertisement