Simple New and Delete
Storage allocated with new must be released with delete.
/* * This program simply shows the use of new to create an object in C++. */ #include <iostream> #include <string> using namespace std; class Fred { public: Fred(string s, int a) { m_val = a; m_lab = s; } int val() { return m_val; } string lab() { return m_lab; } Fred *combine(Fred *other) { return new Fred(lab()+","+other->lab(), val()+other->val()); } private: int m_val; string m_lab; }; int main() { Fred *f1 = new Fred("skunk", 41); Fred *f2 = new Fred("wombat", 33); cout << f1->lab() << ": " << f1->val() << endl; cout << f2->lab() << ": " << f2->val() << endl; Fred *f3 = f1->combine(f2); delete f1; delete f2; cout << f3->lab() << ": " << f3->val() << endl; delete f3; }