// A Demo Class example - written by Lee Devlin 2011-03-01 // This example shows the concepts of default and specific value constructors, // Passing objects by reference and value // The (->) pointer notation to access class members // Declaring a member function outside of its class statement // Example of a destructor which will be executed automatically when // there are no references to a DemoClass object such as when the echo // method (which has a DemoObject called by value) returns. #include using namespace std; class DemoClass { private: char *name; int value; public: DemoClass() // default constructor { name = "default"; value = 5; cout << name << ".DemoClass(" << name << ", " << value << ")\n"; } DemoClass(char *n, int v) // specific value constructor { cout << " " << n << ".DemoClass(" << n << ", " << v << ")\n"; name = n; value = v; } ~DemoClass() // destructor { cout << " " << name << ".~DemoClass() destructor is being executed \n"; } void echo(DemoClass e); void setValue(int v) { cout << " " << name << ".setValue(" << v << ")\n"; value = v; } int getValue() { cout << " " << name << ".getValue()\n"; return value; } int copy(DemoClass &sc) { cout << " " << name << ".copy(" << sc.name << ")\n"; value = sc.value; } }; void DemoClass::echo(DemoClass e) // scope resolution operatore (::) is needed because we are outside of the class { cout << " echo name is " << e.name << " value is " << e.value << endl; } int main() { DemoClass w("w", 100); // next three objects are instantiated with specific values DemoClass x("x", 12); DemoClass y("y", 14); DemoClass n; // this object is set up with the default constructor cout << w.getValue() << endl; cout << n.getValue() << endl; DemoClass* z; // declare a pointer to a class instance z = &y; // assign pointer to instance y cout << "z->getValue is " << z->getValue() << endl; // example of -> pointer notation x.copy(y); cout << x.getValue() << endl; y.setValue(10); cout << y.getValue() << endl; y.echo(y); system("pause"); }