C++ function overriding

前端 未结 6 2247
独厮守ぢ
独厮守ぢ 2020-12-30 01:48

I have three different base classes:

class BaseA
{
public:
    virtual int foo() = 0;
};

class BaseB
{
public:
    virtual int foo() { return 42; }
};

clas         


        
6条回答
  •  盖世英雄少女心
    2020-12-30 02:28

    With BaseA, the child class doesn't compile, the pure virtual function isn't defined

    This is true only if you try to create an object of BaseA. If you create a object of Child and then you can call foo() using either BaseA* or Child*

    With BaseB, the function in the child is called when calling foo on a BaseB* or Child*.

    Depends upon the type of the object as the object can be either BaseB or Child. If the object is BaseB then BaseB::foo is called.

    With BaseC, thefunction in the child is called when calling foo on Child* but not on BaseB* (the function in parent class is called).

    Yes, but you never want to do this.

提交回复
热议问题