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.
Bookmarks