N
Nagrik
Dear Group,
I am calling a function which takes a parameter of type base class and
passing a
concrete (compile time) derived class. The result is that it still
calls the base class
implementation and not the derived class.
For parameter passed as an object, it does not matter whether the
function is
virtual or not, it still calls the base function. And if it is not
virtual all calls are from
base class.
Can someone explain it.
#include "stdafx.h"
#include <iostream.h>
class Pet {
public:
Pet() {}
~Pet() {}
virtual void Say() {cout << "Growl" << endl;}
void nonvirtSay() {cout << "Growl" << endl;}
};
void Make3Sounds( Pet* pptr, Pet& pref, Pet pval);
class Cat : public Pet {
public:
Cat() {}
~Cat() {}
virtual void Say() {cout << "Meaw" << endl;}
void nonvirtSay() {cout << "Meaw" << endl;}
};
int main(int argc, char* argv[])
{
Cat c;
Make3Sounds(&c, c, c);
return 0;
}
void Make3Sounds( Pet* pptr, Pet& pref, Pet pval) {
pptr->Say();
pref.Say();
pval.Say();
pptr->nonvirtSay();
pref.nonvirtSay();
pval.nonvirtSay();
}
Result:
Meaw
Meaw
Growl
Growl
Growl
Growl
Thanks
arun
I am calling a function which takes a parameter of type base class and
passing a
concrete (compile time) derived class. The result is that it still
calls the base class
implementation and not the derived class.
For parameter passed as an object, it does not matter whether the
function is
virtual or not, it still calls the base function. And if it is not
virtual all calls are from
base class.
Can someone explain it.
#include "stdafx.h"
#include <iostream.h>
class Pet {
public:
Pet() {}
~Pet() {}
virtual void Say() {cout << "Growl" << endl;}
void nonvirtSay() {cout << "Growl" << endl;}
};
void Make3Sounds( Pet* pptr, Pet& pref, Pet pval);
class Cat : public Pet {
public:
Cat() {}
~Cat() {}
virtual void Say() {cout << "Meaw" << endl;}
void nonvirtSay() {cout << "Meaw" << endl;}
};
int main(int argc, char* argv[])
{
Cat c;
Make3Sounds(&c, c, c);
return 0;
}
void Make3Sounds( Pet* pptr, Pet& pref, Pet pval) {
pptr->Say();
pref.Say();
pval.Say();
pptr->nonvirtSay();
pref.nonvirtSay();
pval.nonvirtSay();
}
Result:
Meaw
Meaw
Growl
Growl
Growl
Growl
Thanks
arun