inheritance

This is a discussion on inheritance within the C++ Programming forums, part of the General Programming Boards category; I have a class CGeneral. And then I have more classes CClass1, CClass2, ... Each one is a public child ...

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

    inheritance

    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:
    Code:
    class CGeneral {
      MethodOfParentClassCGeneral();
    };
    
    class Class1: public CGeneral {
      MethodOfClass1();
    } obj;
    
    CGeneral *pGen = (CGeneral*)&obj;
    //...
    //...
    // now I need access to instance obj again
    CClass1 *pCl1 = (CClass1*)pGen;
    pCl1->MethodOfClass1();
    pCl1->MethodOfParentClassCGeneral();
    Last edited by larry; 01-21-2002 at 01:58 AM.
    Please excuse my poor english...

  2. #2
    Registered User
    Join Date
    Nov 2001
    Posts
    65
    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
    Location
    NJ
    Posts
    1,141
    You should try to avoid casting really.

    Code:
    CClass1 *pCl1 = (CClass1*)pGen;
    // pCl1->MethodOfClass1(); // try avoid this
    // pCl1->MethodOfParentClassCGeneral(); // instead use the following
    pGen->MethodOfParentClassCGeneral();
    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, 04:03 PM
  2. Virtual inheritance
    By 6tr6tr in forum C++ Programming
    Replies: 13
    Last Post: 05-07-2008, 12:20 PM
  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, 01:46 PM
  5. Inheritance vs Composition
    By Panopticon in forum C++ Programming
    Replies: 11
    Last Post: 01-20-2003, 04:41 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21