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
Re: question about polymorphism in c++
Quote:
Originally Posted by
tpopono
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