///////////////////////////////////////////////////////////////////////////////// // StructWithFunctions.cpp - demonstrates ideas used to build class instances // // // // Jim Fawcett, Summer Short Course, Su2016 // ///////////////////////////////////////////////////////////////////////////////// /* * Found in: Handouts\ShortCourse\Repository\GettingStartedExamples * * This code is written in C Language style, but won't compile as a * C program because we are using C++ strings and streams * */ #include #include // forward struct declaration struct Swf; // function pointer declarations typedef void(*initializerType)(Swf* pThis, const std::string& msg); typedef void(*terminatorType)(Swf* pThis); typedef void(*sayType)(Swf* pThis); struct Swf { // struct holds function pointers static initializerType initializer; // stored in static memory with code static terminatorType terminator; // " static sayType say; // " // struct holds data std::string msg_; // stored with each instance in stack or heap }; // definition of static data - reserves static memory to hold pointer values initializerType Swf::initializer; terminatorType Swf::terminator; sayType Swf::say; //----< constructor >------------------------------------------------ void initializer(Swf* pThis, const std::string& msg) { pThis->msg_ = msg; } //----< destructor >------------------------------------------------- void terminator(Swf* pThis) { pThis->msg_ = ""; } //----< member function >-------------------------------------------- void say(Swf* pThis) { std::cout << "\n " << pThis->msg_.c_str(); } //----< test stub >-------------------------------------------------- int main() { Swf::initializer = initializer; Swf::terminator = terminator; Swf::say = say; Swf s1; s1.initializer(&s1, "Hi, I'm s1"); s1.say(&s1); s1.terminator(&s1); Swf s2; s2.initializer(&s2, "Hello, I'm s2"); s2.say(&s2); s2.terminator(&s2); std::cout << "\n\n"; }