Having trouble understanding why a pointer to a base class is necessary

This is a discussion on Having trouble understanding why a pointer to a base class is necessary within the C++ Programming forums, part of the General Programming Boards category; Hi, Thanks in advance for reading this. Relevant source code files: Author's unmodified copy: virtual.cpp, r21 My modified file: virtual.cpp, ...

  1. #1
    Registered User deoren's Avatar
    Join Date
    Mar 2003
    Posts
    63

    Having trouble understanding why a pointer to a base class is necessary

    Hi,

    Thanks in advance for reading this.



    Relevant source code files:





    The virtual.cpp file is from the book, "C++ Programming in easy steps, 4th edition". Source was found on ineasysteps.com ( http://www.ineasysteps.com/downloads...SourceCode.zip ).

    The topic is, "Calling a virtual method" and the author has this to say:

    "A base class pointer that is bound to a specific derived class can be used to call derived class methods that have been inherited from the base class."

    ...

    "Most usefully, an inherited method in a derived class can override that in the base class when the base method has been delcared as a 'virtual' method."

    ...

    "The declaration of a virtual method indicates that the class will be used as a base class from which another class will be derived, which may contain a method to override the virtual base method."
    It took a long while for that last sentence to make sense, particularly because of the "may contain" part.


    I started playing around with the file (virtual.cpp, r21) and found that by adding/removing the 'virtual' keyword, you get either this output (keyword present):

    I am part of this family, I am the child
    I am part of this family, I am the grandchild
    I am part of this family, I am the parent
    Grandchild has parent and grandparent

    or this output (keyword NOT present):

    I am part of this family, I am the parent
    I am part of this family, I am the parent
    I am part of this family, I am the parent
    Grandchild has parent and grandparent

    I'm still hung up on why a pointer to a base class (Parent in this case) is used to start with, and not just a pointer to one of the derived classes.

    I modified the file (virtual.cpp, r22) and created my own pointers to get the same results. I have two pointers, the author has two pointers, the same result is gained. I'm not really getting this.

    I see that dynamic binding occurs when using the virtual keyword, and I realize that static binding occurs without it, but why is the pointer to a base class used?

    Thanks.
    Last edited by deoren; 02-17-2012 at 04:56 PM. Reason: Changed code blocks to quote blocks for executable output
    It is better to fail with honor than win by deceit
    - unknown

    My erratic tinkerings:
    http://projects.whyaskwhy.org/

  2. #2
    Registered User manasij7479's Avatar
    Join Date
    Feb 2011
    Location
    Kolkata@India
    Posts
    2,523
    Take a look at this: Liskov substitution principle - Wikipedia, the free encyclopedia
    This (and related) answered most of my questions regarding this.
    Manasij Mukherjee | gcc-4.9.2 @Arch Linux
    Slow and Steady wins the race... if and only if :
    1.None of the other participants are fast and steady.
    2.The fast and unsteady suddenly falls asleep while running !



  3. #3
    Registered User
    Join Date
    Nov 2011
    Posts
    48
    This is one of those areas where abstract examples really make learning a concept much more difficult, then if they provide real world, not completely contrived examples.


    You would use a pointer to a base class if you wanted to treat a number of different, but similar objects in the same manner. Chapter 4 of my C++ game tutorial illustrates the use of virtuals in a real world example.


    In a nutshell though, it does something like this ( brutal pseudo code... follow the tutorial if you want to see the full thing ):

    Code:
    struct GameObject {};
    
    struct Player : GameObject {}; 
    
    struct Enemy : GameObjecy{};
    
    vector <GameObjects*> theWorld;
    
    
    main()
    {
    vector<GameObject*> theWorld;
    theWorld.push_back(new Player("Me"));
    theWorld.push_back(new Player("You"));
    theWorld.push_back(new Enemy("Them"));
    
    foreach(Gameobject * obj in theWorld)
     {
       obj->doSomething();
     }
    }

    In this example, other than constructor invocation you are only dealing with pointers to the base class. This allows you to store the different, but similar Player and Enemy classes in the same structure and use the same code.

    By the nature of being a pointer to a virtual method "doSomething", it will call up the function chain to the most inherited implementation. Therefore if Player overrode GameObjects do something, if the GameObject pointer points to a Player object, it will be the Player objects overriden version of doSomething() that will be invoked, not GameObject's.

    If however doSomething() wasn't a virtual method ( but both GameObject and Player had a matching doSomething() method ), the type of the pointer itself would determine which method would be invoked.



    Clear as mud? If not, just click the link and see real world example that is explained a whole lot better!

  4. #4
    Registered User deoren's Avatar
    Join Date
    Mar 2003
    Posts
    63
    Thank you both for the links and the information. I'll be sure to read through the info and reply back with my results.
    It is better to fail with honor than win by deceit
    - unknown

    My erratic tinkerings:
    http://projects.whyaskwhy.org/

  5. #5
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Posts
    23,010
    FYI, references to base classes work too. Not just pointers.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  6. #6
    Registered User deoren's Avatar
    Join Date
    Mar 2003
    Posts
    63

    Smile

    Quote Originally Posted by deoren View Post
    I'm still hung up on why a pointer to a base class (Parent in this case) is used to start with, and not just a pointer to one of the derived classes.
    After rereading Serapth's pseudocode, I finally understood why this is useful. Then, after reading the sections about virtual functions from these books, the how it works finally made sense:



    Out of the those listed, Accelerated C++ and Sams Teach Yourself C++ in 24 Hours gave the best visual representation of what is happening when you assign a derived class address to a pointer to base class.

    It will take me actually practicing with code that uses this approach before I feel comfortable with it, but I at least see how powerful the concept is.

    Thanks to everyone for their help!
    It is better to fail with honor than win by deceit
    - unknown

    My erratic tinkerings:
    http://projects.whyaskwhy.org/

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. base class pointer pointing at derived class
    By mynickmynick in forum C++ Programming
    Replies: 11
    Last Post: 12-01-2008, 12:26 PM
  2. Base-class pointer, accessing object from derived class
    By Korhedron in forum C++ Programming
    Replies: 15
    Last Post: 09-28-2008, 06:30 AM
  3. Replies: 25
    Last Post: 10-29-2007, 05:08 PM
  4. finding derived class type of a pointer to a base class
    By LinuxCoder in forum C++ Programming
    Replies: 15
    Last Post: 04-10-2006, 12:08 PM
  5. Asssign a derived class pointer to a base class?
    By VanJay011379 in forum C++ Programming
    Replies: 3
    Last Post: 07-25-2002, 04:08 PM

Tags for this Thread


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