简体   繁体   中英

Overriding in C++ in a hierarchy of classes

In c++ in this hierarchy of classes

class n1
{
public:
    virtual void tt() { cout << "n1" << endl; }
};
class n2:public n1
{
public:
     void tt() { cout << "n2" << endl; }
};
class n3:public n2
{
    void tt() { cout << "n3" << endl; }
};
int main()
{
    n1 *k = new n3;
    k->tt();
}

In the third class is tt overriding n1 virtual function or it is simply hiding the n2 implementation?

In C# i get that you can override at any level in the hierarchy the virtual method from the lowest class..but i dont know if it is the same in C++.

Class a
{
    virtual void func();
};
class b : a
{
    override func()
};
class c : b
{
    override func()
};

You are overriding it.

If you aren't sure whether your override is correct, we have a keyword called override (c++11 required), which makes sure your override fits the virtual function / method declaration.

This should clear things up:

#include <iostream>
using namespace std;

class n1
{
public:
    virtual void tt() { cout << "n1" << endl; }
};

class n2:public n1
{
public:
    void tt() override { cout << "n2" << endl; }
};

class n3:public n2
{
    void tt() override { cout << "n3" << endl; }
};

int main()
{
    n1 *a = new n1;
    n1 *b = new n2;
    n1 *c = new n3;

    a->tt();
    b->tt();
    c->tt();

    delete a;
    delete b;
    delete c;
}

Outputs:
n1
n2
n3

Live

So in a 3 class hierarchy A->B->C if A has virtual method and B implements it ,it doesnt mean that classes derived from B will take the method already

If you do override it, then that override will be used.

If you don't override the method, then the last overriden method will be used.

class n1
{
public:
    virtual void tt() { cout << "n1" << endl; }
};

class n2:public n1
{
public:
    void tt() override { cout << "n2" << endl; }
};

class n3:public n2
{

};

Outputs:
n1
n2
n2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM