Thread: inheritance

  1. #1
    Registered User larry's Avatar
    Join Date
    Sep 2001


    I have a class CGeneral. And then I have more classes CClass1, CClass2, ... Each one is a public child of CGeneral. Can I create a pointer to CGeneral which can be later casted to pointer to some of its child classes? Like:
    class CGeneral {
    class Class1: public CGeneral {
    } obj;
    CGeneral *pGen = (CGeneral*)&obj;
    // now I need access to instance obj again
    CClass1 *pCl1 = (CClass1*)pGen;
    Last edited by larry; 01-21-2002 at 01:58 AM.
    Please excuse my poor english...

  2. #2
    Registered User
    Join Date
    Nov 2001
    Yes, you can do this. Indeed this type of operations is the heart
    of polymorphism. You can find a lot of detailed information in the Internet or in C++ books about polymorphism also.
    The experimenter who does not know what he is looking for will not understand what he finds.
    - Claude Bernard

  3. #3
    geek SilentStrike's Avatar
    Join Date
    Aug 2001
    You should try to avoid casting really.

    CClass1 *pCl1 = (CClass1*)pGen;
    // pCl1->MethodOfClass1(); // try avoid this
    // pCl1->MethodOfParentClassCGeneral(); // instead use the following
    Instead of casting, use the most general pointer that doesn't need to be casted. Casting itself is an abuse, something to be done perhaps when you have old code that is poorly designed, and don't have the time to do it properly.
    Prove you can code in C++ or C# at TopCoder, referrer rrenaud
    Read my livejournal

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 16
    Last Post: 06-08-2009, 03:03 PM
  2. Virtual inheritance
    By 6tr6tr in forum C++ Programming
    Replies: 13
    Last Post: 05-07-2008, 11:20 AM
  3. Multiple Inheritance - Size of Classes?
    By Zeusbwr in forum C++ Programming
    Replies: 10
    Last Post: 11-26-2004, 09:04 AM
  4. inheritance and performance
    By kuhnmi in forum C++ Programming
    Replies: 5
    Last Post: 08-04-2004, 12:46 PM
  5. Inheritance vs Composition
    By Panopticon in forum C++ Programming
    Replies: 11
    Last Post: 01-20-2003, 04:41 AM