C++ constructs subclass through parent class

Today I saw this sentence:

Members of a derived class can only access protected members of the base class through the derived class object, and derived classes have no access to protected members in a base class object.

That is, if you have the following code:

class A
{
    
    
protected:
	int i;
};
class B :public A
{
    
    
	B(const A& a)
	{
    
    
		this->i = a.i;
	}
};

It cannot be compiled, because the constructor of subclass B cannot access the i member of class A through the parameter a.
Compilation failed
So, how to construct a subclass through the parent class? In C++11, a new thing was added, called the initialization list of the class, which is used after the constructor. The format is as follows:

class 类名
{
    
    
public:
	声明变量;
	构造函数(参数表) :成员变量1(1),成员变量2(2)[,...] {
    
    函数体};
};

Among them, the role of the initialization list is to initialize member variables to the values ​​in parentheses.
E.g:

class A
{
    
    
public:
	int i;
	A(int n) {
    
    
		i = n;
	}
};

can be written as:

class A
{
    
    
public:
	int i;
	A(int n) :i(n) {
    
    };
};

Now, let's go back to the problem above, which can be implemented with an initialization list. code show as below:

#include <iostream>
class A
{
    
    
protected:
	int i;
};
class B :public A
{
    
    
public:
	B(const A& a):A(a)//表示把该对象继承的部分初始化为a
	{
    
    
	}
};

In this way, it can be compiled and passed.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324146618&siteId=291194637