Virtual functions and polymorphism

后端 未结 6 1110
一向
一向 2021-01-24 00:33

Suppose I have this:

class A
{
    public:
    virtual int hello(A a);
};

class B : public A
{
   public:
   int hello(B b){ bla bla };
};

So,

6条回答
  •  时光说笑
    2021-01-24 01:01

    What you are doing there is overloading not overriding, i.e. it's as if class B is:

    class B
    {
    public:
      int hello(A a) {...}
      int hello(B b) {...}
    };
    

    You have two functions of the same name, but with different signatures, which makes them different functions (just like the standard library has different functions for abs(float) and abs(double) etc.)

    If you want to override, then you need to have the same signature, i.e. class B's hello needs to take a parameter of type A. That way, when you call hello on an object of class B, it will use class B's hello rather than class A's.

    If you actually want class B's hello to only accept objects of type B then what you have is fine, although you probably want to make class A's hello non-virtual as you are not really wanting to override it -- you are defining a new function with new parameters and new behaviour.

提交回复
热议问题