Home > OS >  C - What are virtual methods?
C - What are virtual methods?

Time:10-25

Based on this, the following code should print "Running derived method", but when I run it, it prints "Running base method":

#include <iostream>

using namespace std;

class Base
{
public:
    Base() {}
    virtual void run() {cout << "Running base method" << endl;}
    virtual ~Base() {}
};

class Derived : public Base
{
public:
    Derived() {}
    void run() {cout << "Running derived method" << endl;}
    ~Derived() {}
};

int main()
{
    Base o = Derived();
    o.run();
    return 0;
}

CodePudding user response:

There is an answer in the comments, but I have to post it as an answer to close it. Before reading it, I found it out myself by comparing the example code with my code, but the comment was helpful because I now know it's called object slicing. When I assign the value to a variable or field that has the base type, it forgets the original type, and to make it work properly, I have to use pointers

  • Related