Archived

This topic is now archived and is closed to further replies.

paulcoz

Class functions question

Recommended Posts

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

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
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++).

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
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.

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites