6

I was trying to understand the implementation code of "final" in cpp:

following is the code:

/* A program with compilation error to demonstrate that Final class cannot
   be inherited */

class Final;  // The class to be made final

class MakeFinal // used to make the Final class final
{
private:
    MakeFinal() { cout << "MakFinal constructor" << endl; }
friend class Final;
};

class Final : virtual MakeFinal
{
public:
    Final() { cout << "Final constructor" << endl; }
};

class Derived : public Final // Compiler error
{
public:
    Derived() { cout << "Derived constructor" << endl; }
};

int main(int argc, char *argv[])
{
    Derived d;
    return 0;
}

Output: Compiler Error

In constructor 'Derived::Derived()':
error: 'MakeFinal::MakeFinal()' is private

In this I could not understand the logic of virtually inheriting the MakeFinal class. We could simply have inherited it(makeFinal class) as public and even in that case we would have not been able to inherit it further(because the constructor of Makefile is private and only Final class being its friend could have the access of it).

Any pointer??

4

1 回答 1

11

它行不通。非虚拟基类总是由直接从它们派生的类初始化。也就是说,如果场景如下:

class Final : public MakeFinal
{
public:
  Final() {}
};

class Derived : public Final
{};

然后Derived只有初始化的ctor Final,这很好(Final有一个公共ctor)。Final的 ctor 然后初始化MakeFinal,这也是可能的,因为Final是朋友。

但是,对于虚拟基类,规则是不同的。所有虚拟基类都由最派生对象的 ctor 初始化。也就是说,在创建 的实例时Final,它的Finalctor 会初始化MakeFinal。但是,当尝试创建 的实例时Derived,它必须是Derived初始化 的 ctor MakeFinal。这是不可能的,因为MakeFinal的私人 ctor。

另请注意,C++11final为类(和虚函数)引入了关键字。

于 2013-06-19T06:52:05.680 回答