// (C) Porkolab 2003 // // A.4.1. // // Role of constructor // class without constructor: struct node { int val; node *left; node *right; }; int main() { // creation of new object in heap: node *r = new node; // creation in stack: node n; // initialization r->left = r->right = 0; r->val = 5; n.left = n.rigth = 0; n.val = 6; // ... } // class with factory function: struct node { int val; node *left; node *right; }; node create_node( int v) { // creation of new object in heap: node *rp = new node; // initialization rp->left = rp->right = 0; rp->val = v; return r; } int main() { // creates node only in heap node *r = create_node(5); // ... } // class with constructor: struct node { node(int v); int val; node *left; node *right; }; node::node(int v) { val = v; left = right = 0; } int main() { // creation of new object in heap: node *r = new node(5); // creation in stack, equivalent notations: node n1(6); node n2 = 7; node n3 = node(8); // invalid without constructor parameters: node *r = new node; node n; }