Hello Experts,
I was wondering (I'm absolutely new to OOP) if virtual functions are limited in their capability in a sense? Consider the following scenario.
#include <iostream>
using namespace std;
class base
{
public:
virtual int add (int a, int b) {
cout << "Result = " << a + b << endl;
return a + b;
}
};
class derived_float : public base
{
public:
float add (float a, float b) {
cout << "Result = " << a + b << endl;
return a + b;
}
};
int main() {
derived_float dp;
base * bp = &dp;
bp->add (2.5, 4.6);
return(0);
}
I basically can't do this. What I see is,
[nageshg@lx-nageshg1 nageshg]$ g++ test.cpp
test.cpp: In function 'int main()':
test.cpp:27: warning: passing 'double' for argument 1 to 'virtual int base::add(int, int)'
test.cpp:27: warning: passing 'double' for argument 2 to 'virtual int base::add(int, int)'
[nageshg@lx-nageshg1 nageshg]$ l
a.out test.cpp test.sv
[nageshg@lx-nageshg1 nageshg]$ ./a.out
Result = 6
It would have been more powerful if virtual functions which are overridden in derived classes, could behave like overloaded functions. From the current scenario it seems to me that virtual functions are useful for scenarios with,
Same return type
Same argument data types
Same number of arguments
Looks like limited capability. Am I missing anything? The code above is contrived and may not be the best way to express my thoughts. Please excuse...
Thanks,
Nagesh
I was wondering (I'm absolutely new to OOP) if virtual functions are limited in their capability in a sense? Consider the following scenario.
#include <iostream>
using namespace std;
class base
{
public:
virtual int add (int a, int b) {
cout << "Result = " << a + b << endl;
return a + b;
}
};
class derived_float : public base
{
public:
float add (float a, float b) {
cout << "Result = " << a + b << endl;
return a + b;
}
};
int main() {
derived_float dp;
base * bp = &dp;
bp->add (2.5, 4.6);
return(0);
}
I basically can't do this. What I see is,
[nageshg@lx-nageshg1 nageshg]$ g++ test.cpp
test.cpp: In function 'int main()':
test.cpp:27: warning: passing 'double' for argument 1 to 'virtual int base::add(int, int)'
test.cpp:27: warning: passing 'double' for argument 2 to 'virtual int base::add(int, int)'
[nageshg@lx-nageshg1 nageshg]$ l
a.out test.cpp test.sv
[nageshg@lx-nageshg1 nageshg]$ ./a.out
Result = 6
It would have been more powerful if virtual functions which are overridden in derived classes, could behave like overloaded functions. From the current scenario it seems to me that virtual functions are useful for scenarios with,
Same return type
Same argument data types
Same number of arguments
Looks like limited capability. Am I missing anything? The code above is contrived and may not be the best way to express my thoughts. Please excuse...
Thanks,
Nagesh
Comment