Discussion on the use of C++ virtual overload operator virtual operator=

  • 2020-05-10 18:35:08
  • OfStack

Virtual operators in C++, like other virtual functions, can be virtual functions that are dynamically bound, although this is rare. This article takes the assignment operator operator= as an example.

To redefine a base-class virtual function in a derived class, be aware that the parameter must be a reference type to the base class, otherwise it will be completely different from a base-class virtual function and will not be dynamically bound as expected.

In addition to redefining the virtual operators of the base class, derived classes also define their own operator overloads. That is, for every additional layer of derived class, it is theoretically necessary to define one more operator overload.

The following program USES a reference to reference and calls the assignment operator through a pointer (e.g. *p = value) in the same way.


#include <iostream> 
using namespace std; 
               
class Base 
{ 
public: 
  virtual Base& operator=(const Base& rhs) // The overload operator can be set to virtual 
  { 
    cout << "Base" << endl; 
    return *this; 
  } 
}; 
               
class Derived : public Base 
{ 
public: 
  // With the base class operator= Completely different, not redefined, not dynamically bound.  
  // If the operator is not defined, it is synthesized automatically 1 And automatically call the base class operator= No dynamic binding  
  Derived& operator=(const Derived& rhs)  
  { 
    cout << "Derived_D" << endl; 
    return *this; 
  } 
               
  // Redefine the base class operator= , will be dynamically bound  
  //virtual Base& operator=(const Base& rhs) // The return value can be either  
  virtual Derived& operator=(const Base& rhs)  
  { 
    cout << "Derived_B" << endl; 
    return *this; 
  } 
}; 
               
class Derived2 : public Derived 
{ 
  // This kind of need 3 a operator= 
  // Can be defined private the copy Function by 3 a operator= call  
  // You can use dynamic_cast Subclass the base class reference parameter and catch the exception.  
  // If no exception occurs, it is called copy , no assignment is required if an exception occurs  
}; 
               
int main() 
{ 
  Base b1, b2; 
  Derived d1, d2; 
               
  Derived &rd = d1; 
               
  Base &rb1 = b1; // The dynamic type is Base 
  Base &rb2 = d2; // The dynamic type is Derived 
                 
  rb1 = d1; // The output "Base" 
  rb2 = d2; // The output "Derived_B" 
               
  rb1 = rb2; // The output "Base" 
  rb2 = rb1; // The output "Derived_B" 
               
  rd = d1; // The output "Derived_D" 
  rd = b1; // The output "Derived_B" 
                 
  getchar(); 
  return 0; 
}

Related articles: