Type conversion between base class and derived class

An object of a public derived class can be used as an object of a base class, and vice versa is prohibited .

Specifically in:

  • Objects of derived classes can be implicitly converted to objects of base class.
  • Objects of derived classes can initialize references to base classes.
  • A pointer of a derived class can be implicitly converted to a pointer of a base class.

Through the base class object name, the pointer can only use members inherited from the base class

Three situations are shown in the following code:

After the type conversion, the members in the base class can be used; but the base class cannot be converted into an object of a derived class

#include<iostream>
using namespace std;

class A
{
public:
	void show()
	{
		cout << "111" << endl;
	}
	void show1()
	{
		cout << "111222" << endl;
	}
};

class B :public A
{
public:
	void show()
	{
		cout << "222" << endl;
	}
};

void test1(A a)
{
	cout << "派生类的对象可以隐含转换为基类对象:" << endl;
	a.show1();
}

void test2(A* a)
{
	cout << "派生类的指针可以隐含转换为基类的指针:" << endl;
	a->show1();
}

int main()
{
	B b;

	//派生类的对象可以隐含转换为基类对象。
	test1(b);

	//派生类的对象可以初始化基类的引用。
	A &aa = b;

	//派生类的指针可以隐含转换为基类的指针。
	test2(&b);

	cout << "派生类的对象可以初始化基类的引用:" << endl;
	aa.show1();

	system("pause");
	return 0;
}

 

Guess you like

Origin blog.csdn.net/qq_46423166/article/details/112384279