C++ objects - some short, single file demonstrations
Archive - Originally posted on "The Horse's Mouth" - 2011-01-07 06:56:30 - Graham Ellis
One of the key features of the object oriented paradigm is that it provides a system through which code that's naturally associated with one type of data is accessed through a single closely defined and controlled set of calls (its API / Application Programmer Interface) ... so it's natural on a larger project for each data type or group of data types to be separated into their own project / file(s) / teams, allowing for semiasynchronous maintainance. In other words - split, data type by datatype, into managable chunks.
What a great principle! But for a small demo on a course, splitting into multiple files would cause an awful lot of window switching that would obfuscate the initial logic and design elements (or call for an awful lot of projection screen estate!).
So - from yesterday's C++ course - three Object Oriented Examples in C++ which are built in single files, with strong comment lines indication where the application will naturally split across files later.
Firstly principle of an object - a tiny program which does no more that create a really basic object with a property, then look up that property. That's followed by multiple classes and polymorphism, C++ style; virtual methods in a base class, an array of object pointers, and calls to methods of the same name, but in different classes, which the language itself resolves dynamically at runtime. The final one of these three examples shows some more advanced features such as overloading and deconstructors - things which you'll need from time to time, but not often in such a short program as this.
Rather than continue to grow this example, I illustrated the technique for comparing objects in C++ in a separate example [here] at the end of the day - that brought in a static method to the equation too. There's a fuller description of that [here], and a further source example - showing it split into multiple files (what I'll be doing from 9 a.m. this morning) [here].