virtual functions not working

Nibbie
Posts: 2
Joined: 2010.12
Post: #1
to simplify, it looks like virtual functions are not working proper, the derived function is not called, but just the base
Code:
-------------------------------------------
class Base {
     virtual void foo();
}

void Base::foo() {
     printf("BASE");
}
-------------------------------------------
class Derived: public Base {
     void foo();
}

void Derived::foo() {
     printf("DERIVED");
}
-------------------------------------------
void test(BASE * basePointer) {
    basePointer->foo();
}
-------------------------------------------
Derived * D = new Derived();
test(D);

outputs BASE Sad
should it output DERIVED??

thank you
Quote this message in a reply
Luminary
Posts: 5,143
Joined: 2002.04
Post: #2
I made your code compilable:

Code:
#include <stdio.h>
//-------------------------------------------
class Base {
public:
virtual void foo();
};

void Base::foo() {
printf("BASE\n");
}
//-------------------------------------------
class Derived: public Base {
public:
void foo();
};

void Derived::foo() {
printf("DERIVED\n");
}
//-------------------------------------------
void test(Base * basePointer) {
basePointer->foo();
}
//-------------------------------------------
int main(){
Derived * D = new Derived();
test(D);
}

And compiled and ran it:
Code:
OneSadMBP13:Desktop keith$ g++ test.cc
OneSadMBP13:Desktop keith$ ./a.out
DERIVED
Quote this message in a reply
Apprentice
Posts: 8
Joined: 2011.03
Post: #3
Of course it should print "Derived". D is declared as a Derived *, not a Base * in main(). By the way, you should prefer to include <cstdio> over <stdio.h>. <cstdio> declares everything in <stdio.h> in the std namespace.
Quote this message in a reply
Post Reply 

Possibly Related Threads...
Thread: Author Replies: Views: Last Post
  exporting c functions and variables NelsonMandella 6 4,642 Apr 1, 2010 05:07 PM
Last Post: NelsonMandella
  Haskell Data Types and Functions wyrmmage 1 3,268 Mar 4, 2008 05:25 PM
Last Post: OneSadCookie
  Virtual method segfault (C++) sealfin 4 4,027 Dec 4, 2006 04:10 AM
Last Post: sealfin
  Virtual functions/Inheritance. BinarySpike 5 4,078 Sep 29, 2005 11:16 AM
Last Post: BinarySpike
  Mac memory status functions? Puzzler183 8 5,390 May 1, 2005 02:36 PM
Last Post: Puzzler183