//----------------------------------------------------------------------------- // name: X.cpp // desc: basic class and inheritance example // // Music 256a, Fall 2009, Stanford University // http://ccrma.stanford.edu/courses/256a-fall-2009/ // // compile: // g++ -o X X.cpp // run: // ./X //----------------------------------------------------------------------------- #include "X.h" // get an instance of Foo Foo * Foo::getInstance() { if( ourFoo == NULL ) ourFoo = new Foo(); return ourFoo; } // Foo's void Foo::sayHello() { cerr << "hello, I am a Foo" << endl; cerr << m_publicVar << " " << m_protectedVar << " " << m_privateVar << endl; } // overloaded void Foo::sayHello( int num ) { for( int i = 0; i < num; i++ ) { sayHello(); } } // constructor Foo::Foo() { cerr << "Foo()" << endl; m_publicVar = 0; m_protectedVar = 0; m_privateVar = 0; } // destructor Foo::~Foo() { cerr << "see ya" << endl; } // static instantiation Foo * Foo::ourFoo = NULL; int Foo::ourStaticVar = 0; // constructor FooBar::FooBar() { cerr << "FooBar()" << endl; } // overrides parent class's void FooBar::sayHello() { cerr << "no! I don't want to say hello! I am a FooBar, and a Foo" << endl; } // entry point int main() { // instantiate // Foo * foo = Foo::getInstance(); Foo * foo = new FooBar(); // assign 10 foo->m_publicVar = 10; // say hello foo->sayHello( 10 ); // access static var (without instance) Foo::ourStaticVar = 50; // access the same static var (through instance) foo->ourStaticVar = 10; // reclaim foo delete foo; return 0; }