In Java you can use the New operator to create an object from Free System Memory and assign it to a Reference. In C++ you have to use New with Pointers.
I thought well, what if I make a reference to the pointer and then delete it to avoid memory leaks later. I thought this would a be a cool work around, but alas it didn't work.
PHP Code:
#include <iostream>
using namespace std;
class v3
{
private:
int x;
int y;
int z;
public:
v3(int X = 0, int Y = 0, int Z = 0)
{
x = X;
y = Y;
z = Z;
}
void print( void )
{
cout << "x: " << x << " y: " << y << " z: " << z << "\n";
cout << "\n\n\n\n";
}
};
int main()
{
cout << " Program memory v3 variable v" << "\n\n";
v3 v( 36, 24, 36 );
v.print();
v3* vp = new v3( 44, 27, 40 );
cout << " Free memory using new operator creating pointer vp" << "\n\n";
vp->print();
v3& vr = *vp;
cout << " vr reference to the pointer vp" << "\n\n";
vr.print();
delete vp;
cout << " Deleted pointer vp to avoid memory leaks" << "\n\n\n\n";
cout << " Our reference vr has garbage now" << "\n\n";
vr.print();
cout << " Shame that you can't use the new operator with references in c++" << "\n";
cout << " like you can in Java. I thought perhaps this work around would have worked" << "\n";
cout << " but it didn't." << "\n\n";
cout << " Press Enter to Exit" << "\n\n";
cin.get();
return 0;
}
Bookmarks