虚拟继承及其在防止继承中的用途 [英] virtual inhertence and its use in preventing inheritence

查看:60
本文介绍了虚拟继承及其在防止继承中的用途的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



如果可能的话,当我们使用虚拟继承构造密封类时,有人可以帮我告诉我内部发生了什么吗?
我有以下两个代码段:两者之间的唯一区别是virtual关键字.但是,如果我们不使用它,那么行为将与预期不符.请帮我为什么会这样?

Hi,

If possible, can someone help and tell me what happens in internal when we use virtual inhertence to construct a sealed class?
I have the following two code snippet: The mere difference between the two is the virtual keyword. But if we don''t use it, then , behaviour is not as expected.Please help me why it is so?

#include<iostream>

using namespace std;

class Base;

class final_lock
{
                friend class Base;
        private:
                final_lock() {}
                final_lock(const final_lock&) {}
};

class Base : public virtual final_lock { ///// Here virtual is necessary... why is it so? How does it make any difference internally?

public:
        Base() { }
        Base(char*) {}
        void fun(){ cout<<"I am in base"<<endl; }

};


class Der : public Base { };

int main()
{
        ///Der dd; // Cannot construct a Der obj... why it it so?
        ///dd.fun();
        Base m;
}





#include<iostream>

using namespace std;

class Base;

class final_lock
{
                friend class Base;
        private:
                final_lock() {}
                final_lock(const final_lock&) {}
};

class Base : public final_lock { //// Here virtual is not present.

public:
        Base() { }
        Base(char*) {}
        void fun(){ cout<<"I am in base"<<endl; }

};


class Der : public Base { };

int main()
{
        Der dd; /// Here we can construct a  Der obj!!!!!
        dd.fun();
        Base m;
}



我知道使用虚拟继承后会构造一个vptr,并且首先构造虚拟基类.但是,它对进行密封课有什么帮助呢?请在内部告诉我它是如何发生的?如果不清楚我的问题,请告诉我.



I know a vptr is being constucted after use use virtual inheritence and the virtual base class is being constructed first. But how does it help in making sealed class? Please tell me internally what make it happen? Please let me know if I am not clear with my problem.

推荐答案

请参见 [^ ].

它指出:

See "Inheritance - multiple and virtual inheritance: What special considerations do I need to know about when I inherit from a class that uses virtual inheritance?"[^].

It states:


最派生类的ctor的初始化列表直接调用虚拟基类的ctor.

Initialization list of most-derived-class''s ctor directly invokes the virtual base class''s ctor.


:)


这篇关于虚拟继承及其在防止继承中的用途的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆