Path: utzoo!utgpu!jarvis.csri.toronto.edu!cs.utexas.edu!tut.cis.ohio-state.edu!att!dptg!ulysses!andante!alice!ark From: ark@alice.UUCP (Andrew Koenig) Newsgroups: comp.lang.c++ Subject: Re: Novice question re: class derivation Message-ID: <10354@alice.UUCP> Date: 19 Jan 90 14:07:43 GMT References: <44.UUL1.3#5109@pantor.UUCP> Organization: AT&T Bell Laboratories, Liberty Corner NJ Lines: 74 In article <44.UUL1.3#5109@pantor.UUCP>, richard@pantor.UUCP (Richard Sargent) writes: > So the bottom line is: How can I set up a hierarchy of device > classes that will allow me to code (my main application, at least) > to be independent of the display device? I don't see anything wrong with what you've done so far. You're missing just one little trick. The idea is to never use the object directly. Rather, refer to it through a pointer or reference to a base class object. For example: class Display { /* ... */ }; class ColorDisplay: public Display { /* ... */ }; class HighResDisplay: public Display { /* ... */ }; Somewhere you have to make a decision on what kind of display you're using. Probably the most direct way to do it is something like this: Display* dp; if (cond1) dp = new ColorDisplay; else if (cond2) dp = new HighResDisplay; else /* ... */ Now you code all display operations in terms of pointer operations on dp dp->clear(); dp->draw(image); // and so on When you're finally done, you can free it: delete dp; but for this to work, your Display base class must have a virtual destructor. Perhaps a better way of structuring it, if you can, is to do all the real work in a subroutine that takes the Display object as a formal parameter. Then the allocating and freeing are done in one routine and everything else is done somewhere else. If you do this, you can make that parameter a reference to a Display rather than a pointer to a Display, which you may find more natural: void MyApplication(Display& d) { // ... d.clear(); // and so on } main() { if (cond1) { ColorDisplay d; MyApplication(d); } else if (cond2) { // ... } // ... } Now you don't have to allocate and free Display objects on the free store -- they're local to the various branches of the `if'. Hope this helps. -- --Andrew Koenig ark@europa.att.com