question about polymorphism in c++
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2

Thread: question about polymorphism in c++

Hybrid View

  1. #1
    Join Date
    Dec 2012
    Posts
    1

    question about polymorphism in c++

    Hello, im starting out in c++ and i want to know why this code prints out base

    Code:
    struct base 
    {
        virtual void foo(void){
            cout<<"base"<<endl;
        }
     }
     struct derived : base(void)
     {
       void foo(void){
           cout<<"derived"<<endl;
       }
     }
     
    int main (void)
     {
     base *b = new derived;
     b -> foo();
     return 0
     }
    i know that when making a program like this in java the output would be derived.. I would like to know how it works in c++. thank you for your time

  2. #2
    Join Date
    Apr 1999
    Posts
    27,446

    Re: question about polymorphism in c++

    Quote Originally Posted by tpopono View Post
    Hello, im starting out in c++ and i want to know why this code prints out base
    That code doesn't even compile. Next time, post real code. We have no idea why you get output with a program that is not the one you posted.
    Code:
    #include <iostream>
    using namespace std;
    
    struct base 
    {
        virtual void foo(void){
            cout<<"base"<<endl;
        }
    };
    
    struct derived : base
    {
       void foo(void){
           cout<<"derived"<<endl;
        }
    };
    
    int main ()
    {
         base *b = new derived;
         b -> foo();
         return 0;
    }
    The following prints out "derived". However, there is a problem with it in that

    1) The code has a memory leak (Java is not C++ -- the usage of new in Java is not the same as in C++). Please do not use Java as a model in learning C++ as it just leads to confusion, both in learning the proper C++ fundamentals and in writing C++ code.

    2) The base class should have a virtual destructor, since you are using base class pointers, dynamically allocated memory, and accessing virtual functions through the base class pointer.

    Regards,

    Paul McKenzie

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center