The parent class pointer points to the subclass object and the parent class reference points to the subclass object

C++ is divided into static polymorphism and dynamic polymorphism. Dynamic polymorphism is achieved by subclasses rewriting the base functions of the parent class.

The parent class pointer points to the child class object

#include <iostream>  
  
class Parent {
    
      
public:  
    virtual void print() {
    
      
        std::cout << "Parent" << std::endl;  
    }  
};  
  
class Child : public Parent {
    
      
public:  
    void print() {
    
      
        std::cout << "Child" << std::endl;  
    }  
};  
  
int main() {
    
      
    Child c;
    Parent* parentRef =&c; // 父类引用指向子类对象  
    parentRef->print(); // 输出 "Child"  
    return 0;  
}

Parent class reference points to child class object

#include <iostream>  
  
class Parent {
    
      
public:  
    virtual void print() {
    
      
        std::cout << "Parent" << std::endl;  
    }  
};  
  
class Child : public Parent {
    
      
public:  
    void print() {
    
      
        std::cout << "Child" << std::endl;  
    }  
};  
  
int main() {
    
      
    Child c;
    Parent& parentRef =c; // 父类引用指向子类对象  
    parentRef.print(); // 输出 "Child"  
    return 0;  
}

The overridden function of the parent class must be added virtual, otherwise there is no way to rewrite it, and the final output will still be Parent

Guess you like

Origin blog.csdn.net/qaaaaaaz/article/details/132701891