/* * Program to illustrate that class instaces in C++ can be created on the * stack (without new), unlike Java. Passing class instances to functions, * and during assignment statements create "a copy" of the actual/RHS * variable instance. */ #include using namespace std; // CHANGE1: Change dynamic allocation of class variable to static // allocation. All fields in the structure are not passed "by value". // Any change made in "frap" will not be reflected in "main". #define CHANGE1 0 // CHANGE2: Passing the class variable "by reference". Any changes made in // "frap" are now visible in "main" (similar to Java behavior). #define CHANGE2 0 class Blip{ public: int local; #if CHANGE1 // Change1: to "int ptr[2]", and see what happens. int ptr[2]; #else int *ptr; #endif }; #if CHANGE2 // Change2: to "void frap(Blip &arg)" void frap(Blip &arg) #else void frap(Blip arg) #endif { cout << "Frap: START function: local: " << arg.local << " ptr[0]: " << arg.ptr[0] << " ptr[1]: " << arg.ptr[1] << endl << endl; arg.local = 200; arg.ptr[0] = 10; arg.ptr[1] = 20; cout << "Frap: END function: local: " << arg.local << " ptr[0]: " << arg.ptr[0] << " ptr[1]: " << arg.ptr[1] << endl << endl; } int main() { Blip main_b; main_b.local = 100; #if !CHANGE1 // Change1: Comment out this line. main_b.ptr = new int[2]; #endif main_b.ptr[0] = 1; main_b.ptr[1] = 2; cout << "Main: Values BEFORE function call: local: " << main_b.local << " ptr[0]: " << main_b.ptr[0] << " ptr[1]: " << main_b.ptr[1] << endl << endl; frap(main_b); cout << "Main: Values AFTER function call: local: " << main_b.local << " ptr[0]: " << main_b.ptr[0] << " ptr[1]: " << main_b.ptr[1] << endl << endl; return 0; }