Please find the bug in the code...

0 Superman HC · June 28, 2015
I have tried polymorphism the normal way.. it works fine...
I have tired virtual function the normal way... it works fine..
Now i am trying to pass parameter to a virtual function so that it gives different message for different object and the message is to be passed as a parameter in main function... it is NOT WORKING...

The code that is used is :


using namespace std;

class mainclass{

        virtual void print(string a){
        string message;

class fclass:public mainclass{

    void print(){
        cout<< "From : Taylor Swift "<<message<<endl;

class sclass:public mainclass{

    void print(){
        cout<< "From : Eddie Goulding "<<message<<endl;

int main(){

    fclass f;
    sclass s;

    mainclass *m1=&f;
    mainclass *m2=&s;

    m1->print("RV is the best");
    m2->print("RV is the coolest");
return 0;

Kindly tell me if there is any bug in the code... or is it not possible to perform it in this way...
Thanks in advance..

Post a Reply


Oldest  Newest  Rating
0 Alper Akgoz · June 29, 2015
There isn't any bug in the code. m1 and m2 are mainclass objects so you are calling the print function in mainclass, which isn't really printing anything just setting message equal to a. If you do f.print() and s.print() it prints the messages.
0 Superman HC · June 29, 2015
yea but that's the case with normal polymorphism functions... as far as I have learned.. virtual functions automatically refer to the derived class and one doesn't need to call the specific functions from the object... 
+1 Alper Akgoz · June 29, 2015
Yeah, but your code sets the message property, because you are passing an argument, while print function in derived classes don't take in any arguments. So the function in mainclass is called because it matches the print function called in main. It works if print function in derived classes take in message as argument.
0 Superman HC · June 29, 2015
oo yea... got it... works..
0 Alper Akgoz · June 29, 2015
You're welcome :)
  • 1



Used in many types of software including music players, video games, and many large scale applications.

Bucky Roberts Administrator