this is so wierd...there must be invisible characters on my screen that keeps dev-cpp from compiling it:
Here's the code that comes with the book that DID compile:
Code:
// Programming with C++, Second Edition, by John R. Hubbard
// Copyright McGraw-Hill 2000
// Example 12.12, page 285
// Memory Leaks
#include <iostream>
#include <cstdlib>
using namespace std;
class X
{
public:
X() { p = new int[2]; cout << "X(). "; }
~X() { delete [] p; cout << "~X().\n"; }
private:
int* p;
};
class Y : public X
{
public:
Y() { q = new int[1023]; cout << "Y():T::q = " << q << ". "; }
~Y() { delete [] q; cout << "~Y(). "; }
private:
int* q;
};
int main()
{
for (int i = 0; i < 8; i++)
{
X* r = new Y;
delete r;
}
system("pause");
return 0;
}
... and here's the code i typed in myself directly from the book with added comments that DID NOT COMPILE:
Code:
// Virtual Destructors and Memory Leaks
// an explicit destructor may be defined to be virtual
// the following example illustrates the value in defining
// a virtual destructor
//
// since r is declared to be a pointer to X objects, only
// the X destructor is invoked, deallocating only 8 bytes
// so on each iteration 4029 bytes are lost!
#include <iostream>
#include <cstdlib>
using namespace std;
class X
{ public:
X() { p = new int[2]; cout << "X(). "; }
~X() { delete [] p; cout << "~X().\n"; }
private:
int* p;
};
class Y
{ public:
Y() { q = new int[1023]; cout << "Y(): Y::q = " << q << ". "; }
~Y() { delete [] q; cout << "~Y(). "; }
private:
int* q;
};
int main()
{ for (int i=0; i<8; i++)
{ X* r = new Y;
delete r;
}
system("pause");
return 0;
}
and here's the error msg the compiler spits out:
Compiler: Default compiler
Executing g++.exe...
g++.exe "C:\C\Code\MemLeak.cpp" -o "C:\C\Code\MemLeak.exe" -Wall -I"C:\DEVCPP\include\c++" -I"C:\DEVCPP\include\c++\mingw32" -I"C:\DEVCPP\include\c++\backward" -I"C:\DEVCPP\include" -L"C:\DEVCPP\lib"
C:/C/Code/MemLeak.cpp: In function `int main()':
C:/C/Code/MemLeak.cpp:33: cannot convert `Y*' to `X*' in initialization
Execution terminated
I'm not crazy, right?
Swaine777