virtual functions not working
to simplify, it looks like virtual functions are not working proper, the derived function is not called, but just the base
outputs BASE
should it output DERIVED??
thank you
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

should it output DERIVED??
thank you
I made your code compilable:
And compiled and ran it:
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
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.
Possibly Related Threads...
| Thread: | Author | Replies: | Views: | Last Post | |
| exporting c functions and variables | NelsonMandella | 6 | 4,292 |
Apr 1, 2010 05:07 PM Last Post: NelsonMandella |
|
| Haskell Data Types and Functions | wyrmmage | 1 | 3,016 |
Mar 4, 2008 05:25 PM Last Post: OneSadCookie |
|
| Virtual method segfault (C++) | sealfin | 4 | 3,647 |
Dec 4, 2006 04:10 AM Last Post: sealfin |
|
| Virtual functions/Inheritance. | BinarySpike | 5 | 3,831 |
Sep 29, 2005 11:16 AM Last Post: BinarySpike |
|
| Mac memory status functions? | Puzzler183 | 8 | 5,138 |
May 1, 2005 02:36 PM Last Post: Puzzler183 |
|

