The role and application of subtypes

1. The role of the subtype:
wherever an object of the parent class is needed, an object of the "public derived" subclass can be used instead,
so that the same function can be used to uniformly handle the base class object and the public derived class object. That is
: when the formal parameter is a base class object, the actual parameter can be a derived class object

#include <iostream>

using namespace std;

class Father {
    
    
public:
	void play() {
    
    
		cout << "KTV唱歌!" << endl;
	}
};

class Son : public Father {
    
    
public:
	void play() {
    
    
		cout << "今晚吃鸡!" << endl;
	}
};


void party(Father *f1, Father *f2) {
    
    
	f1->play();
	f2->play();
}

int main(void) {
    
    
	Father yangKang;
	Son yangGuo;

	party(&yangKang, &yangGuo);

	system("pause");
	return 0;
}

The output is:
insert image description here
Note: If you change Son to protected inheritance or private inheritance, compilation will fail!

Second, the application of subtypes
1. The pointer of the base class (parent class) can point to the public derived class (subtype) object of this class.

Son yangGuo;
Father * f = &yangGuo;

2. Objects of public derived classes (subtypes) can initialize references to base classes

Son yangGuo;
Father &f2 = yangGuo;

3. Objects of public derived classes can be assigned to objects of base classes

Son yangGuo;
Father f1 = yangGuo;

Note: The above application, in turn, will fail to compile!

Guess you like

Origin blog.csdn.net/weixin_46060711/article/details/123932943