// Example C++ Classes // George F. Riley, Georgia Tech, Spring 2009 #include // Needed for the "cout" commands using namespace std; // Define a C Structure called TwoInt_t typedef struct { int a; int b; } TwoInt_t; void PrintTwo(TwoInt_t* ti) { cout << "a " << ti->a << " b " << ti->b << endl; } // Define a second structure with TwoInt_t as an element typedef struct { TwoInt_t ti; int c; int d; } FourInt_t; void PrintFour(FourInt_t* fi) { cout << "a " << fi->ti.a << " b " << fi->ti.b << " c " << fi->c << " d " << fi->d << endl; } // Define a C++ Class that does the same thing as TwoInt_t class TwoInt { public: int a; int b; }; void PrintTwo(TwoInt* ti) { cout << "a " << ti->a << " b " << ti->b << endl; } // Define a C++ Class that does the same thing as TwoInt_t // plus a "Constructor" class TwoIntC { public: TwoIntC(); public: int a; int b; }; //NewPage // Code for TwoIntC constructor TwoIntC::TwoIntC() { a = 1000; b = 1001; } void PrintTwo(TwoIntC* ti) { cout << "a " << ti->a << " b " << ti->b << endl; } // Demonstrate a C++ "reference" argument. // More about this later in the semester void PrintTwo(const TwoIntC& ti) { cout << "a " << ti.a << " b " << ti.b << endl; } // Make a subclass of TwoIntC called FourInt class FourInt : public TwoIntC { public: FourInt(); // Constructor public: int c; int d; }; // Code for FourInt constructor FourInt::FourInt() : TwoIntC() { c = 3001; d = 3002; } // Define a subroutine to print FourInt variables c and d void PrintFour(FourInt* fi) { cout << "c " << fi->c << " d " << fi->d << endl; } //NewPage int main() { TwoInt_t a; // Uninitialized // Print the uninitialized one PrintTwo(&a); // Declare another one, and initialize it TwoInt_t b; // Initialized below b.a = 1; b.b = 2; PrintTwo(&b); // Declare a FourInt variable FourInt_t f; f.ti.a = 10; f.ti.b = 11; f.c = 12; f.d = 13; PrintFour(&f); // Now try a trick. Pass the FourInt variable to PrintTwo PrintTwo((TwoInt_t*)&f); //PrintTwo(&f); // Declare a variable of class TwoInt TwoInt cTi; // Since we have no constructor in class TwoInt, a and b are random PrintTwo(&cTi); // Initialize a and b to good values. cTi.a = 20; cTi.b = 21; PrintTwo((TwoInt_t*)&cTi); // Declare a variable of class TwoIntC TwoIntC cTiC; PrintTwo(&cTiC); // Call the PrintTwo with the reference argument PrintTwo(cTiC); // Declare a variable of class FourInt FourInt fi; PrintTwo(&fi); // Note we are calling the "TwoInt" printer PrintFour(&fi); }