Ask your own question, for FREE!
Computer Science 7 Online
OpenStudy (anonymous):

Can someone explain me "Function Overriding and polymorphism in C++" Give me some examples.

OpenStudy (turingtest):

Didn't I answer this yesterday? Did you not understand my explanation? double area(double radius) { return 3.14*radius*radius; } double area(double width, double height) { return width * height; } This is an overloaded function called area. Calling area in main will call either the first version or the second depending on how many argument you pass to it: int main() { double x, y, circle, rectangle; circle = area(x); //This will call the first declaration of area rectangle = area(x, y); //This will call the second declaration of area return 0; } Is this clear enough for you, or are you confused?

OpenStudy (anonymous):

I have tried to understand this way. #include<iostream> using namespace std; void printNumber(int x) { cout<<"I am printing an integer<<x<<endl; } void printNumber(int x) { cout<<"I am printing a float<<x<<endl; } int main() { int a=54; float b=3.154; printNumber(a); printNumber(b); }

OpenStudy (turingtest):

that won;t work because both versions of printNumber that you wrote take the same number and type of argument one int the key to function overloading is to make two versions of a function that take *different numbers and/or types* of arguments i.e. printNumber(char c) printNumber(int x) printNumber(int x, char c) all these are overloads, but you *cannot* make another such as printNumber(int n) because this takes the same number of arguments, just one int, and we already have a version of printNumber that does that

OpenStudy (anonymous):

#include<iostream> using namespace std; void printNumber(int x) { cout<<"I am printing an integer<<x<<endl; } void printNumber(float x) \\i made a mistake here. i corrected it { cout<<"I am printing a float<<x<<endl; } int main() { int a=54; float b=3.154; printNumber(a); printNumber(b); }

OpenStudy (turingtest):

You have the right idea.this would be a valid overload, but I'd avoid trying to distinguish an overridden function by a difference like int, float, double, etc, since a float may accidentally become an int during a program's execution, or a float may be promoted to a double, causing confusing behavior for the programmer. It's bad practice, but technically viable.

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!