Questions

Hi, everyone!

There are 2 questions at the end, check it out. Thanks.


#include <iostream.h>
#include <string.h>
#include <stddef.h>
const int MAXNAMES = 100;
class Name
{
public:
Name( const char *s ) {
strncpy( name, s, 25 );
}
void display() const { cout << '\n' << name; }
void * operator new ( size_t size );
void operator delete( void * ptr );
~Name() {}; // do-nothing destructor
private:
char name[25];
};

// -------- Simple memory pool to handle fixed number of Names
char pool[MAXNAMES] [sizeof( Name )];
int inuse[MAXNAMES];
// -------- Overloaded new operator for the Name class
void * Name :: operator new( size_t size )
{
for( int p = 0; p < MAXNAMES; p++ )
if( !inuse[p] )
{
inuse[p] = 1;
return pool + p;
}
return 0;
}
// --------- Overloaded delete operator for the Names class
void Name :: operator delete( void *ptr )
{
inuse[((char *)ptr - pool[0]) / sizeof( Name )] = 0;
}
void main()
{
Name * directory[MAXNAMES];
char name[25];
for( int i = 0; i < MAXNAMES; i++ )
{
cout << "Enter name # " << i+1 << ": ";
cin >> name;
directory[i] = new Name( name );
}
for( i = 0; i < MAXNAMES; i++ )
{
directory[i]->display();
delete directory[i];
}
}

/*what " pool + p" will return, because "pool" is the name of array and "p" is an integer?

what is the meaning of "if( !inuse[p] )", written in "new" operator over-loading ?

Thanks.
*/
Hi,

what " pool + p" will return, because "pool" is the name of array and "p" is an integer?



It is an example of pointer arithmetic. The name of an array is equivalent to the address of the array, if one adds an int n to it, then the n'th item in the array is returned. In this example, pool + p is the same as pool[p]


what is the meaning of "if( !inuse[p] )", written in "new" operator over-loading ?


Not sure what you mean by "written in "new" operator over-loading".

If inuse[p] is zero, then that expression evaluates to false. However it is reversed by the ! (not) operator. So the expression literally means "if not in use".

This code is a good example of mixing C and C++ code, which is usually considered bad form.

main() returns an int, it can never be void, but you are probably using the ancient Turbo C++, which is over 20 years old and doesn't comply with modern C++ standards.
Topic archived. No new replies allowed.