Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ virtual function simple example

Tags:

c++

Trying to get a quick understanding of how virtual functions work and not sure why the code below doesn't print any output. As far as I know, since moveMouth() is virtual, it should use the version of moveMouth() in the talk class.

/*
 * main.cpp
 *
 *  Created on: Mar 29, 2015
 *      Author: Admin
 */

#include <iostream>

using namespace std;

class talk{

public:

    int a=5;
     void moveMouth(){
        cout <<"blah blah blah"<<endl;
    }
};

class person : public talk {

public:
    int id;
    person(int a): id(a) {

    }

    virtual void moveMouth(){
        //cout <<"word word word"<<endl;
    }


};

int main(){
    person* p = new person(0);
    p->moveMouth();
    return 0;
}
like image 804
Sentinel Avatar asked Dec 19 '22 03:12

Sentinel


1 Answers

As far as I know, since moveMouth() is virtual, it should use the version of moveMouth() in the talk class.

No, that's not how polymorphism works. It allows you to introduce different behavior in the derived class when used in the base class.

Your example calls the empty implementation of moveMouth() from the person class.

To call the base class version just omit the declaration in the derived class:

class person : public talk {
public:
    int id;
    person(int a): id(a) {

    }

    // Completely omit this if you want to call the base class function by default:
    // virtual void moveMouth(){
        //cout <<"word word word"<<endl;
    // }
};

To allow to change the behavior, you must declare the function as virtual in the base class:

class talk{

public:

    int a=5;
     virtual void moveMouth(){
  // ^^^^^^^
        cout <<"blah blah blah"<<endl;
    }
};

The polymorphic behavior in the inheritance hierarchy starts from the point you first introduce a virtual function.


As an aside:
Polymorphic behavior can be better demonstrated like this

int main(){
    talk* t = new person(0);
    t->moveMouth();
    return 0;
}
like image 117
user0042 Avatar answered Dec 24 '22 01:12

user0042