override keyword

https://www.cnblogs.com/xinxue/p/5471708.html

2 override (the override)

  Override keyword mentioned in 1.2.2 to avoid errors rewrite forget derived class virtual function

  The following four errors to override the virtual function, easy to make an example, the detail

Copy the code
class Base {
public:
    virtual void mf1() const;
    virtual void mf2(int x);
    virtual void mf3() &;
    void mf4() const;    // is not declared virtual in Base
};

class Derived: public Base {
public:
    virtual void mf1();        // declared const in Base, but not in Derived.
    virtual void mf2(unsigned int x);    // takes an int in Base, but an unsigned int in Derived
    virtual void mf3() &&;    // is lvalue-qualified in Base, but rvalue-qualified in Derived.
    void mf4() const;        
};
Copy the code

  In a derived class, override (override) Following the realization (implementation) Chengzi Ji class member function, to meet the following conditions:

  A virtual : the base class member function is declared virtual (virtual)

  Two receiving : a base class and derived classes, types, and member function returns the exception specification (exception specification) must be compatible

  Four of : the base class and a derived class, member function name, parameter types, constants attributes (constness) and references qualifiers (reference qualifier) must be identical

  So restricted conditions, resulted in virtual function rewrite the code as described above, since a very easy and careless mistakes

  C ++ 11 in the override keyword, you can explicitly declared in a derived class, what member functions need to be rewritten, if not be rewritten, the compiler will complain.

Copy the code
class Derived: public Base {
public:
    virtual void mf1() override;
    virtual void mf2(unsigned int x) override;
    virtual void mf3() && override;
    virtual void mf4() const override;
};
Copy the code

  Thus, even if accidentally left out the harsh conditions of a virtual function rewrite, or by being given the compiler, quickly correct mistakes

Copy the code
class Derived: public Base {
public:
    virtual void mf1() const override;  // adding "virtual" is OK, but not necessary
    virtual void mf2(int x) override;
    void mf3() & override;
    void mf4() const override; 
}; 
Copy the code

 

summary:

1)   public inheritance

  Pure virtual function => inheritance are: an interface (interface)

  Common virtual function => inheritance are: the interface and achieve the default (default implementation)

  Non-virtual member function => inheritance are: the interface and enforced (mandatory implementation)

2) Do not redefine a relay Chengzi Ji class non-virtual functions  (Never the redefine  AN Inherited Virtual non-function)

3) After the function declaration needs to be rewritten, add keywords  override

Guess you like

Origin www.cnblogs.com/xiangtingshen/p/11089118.html