Same named Variables In C++ inheritance

来源:互联网 发布:黑鹰基地vb教程 编辑:程序博客网 时间:2024/06/05 03:42

Test Objective:

In a case that there is 2 same named variables seperately locate in a parent class and one of its possible child classes, what c++ will deel with the 2 variables?

Test Enviroment:

en VS 2008


Test code:

class Base {public:Base(){ m_d = 0; }virtual ~Base(){ printf("destroy Base mem\n"); }virtual int d_func(){ return m_d;}int m_d;};class Derived : public Base{public:Derived() { m_d = 1;}~Derived(){ printf("destroy Derived mem\n"); }int d_func(){ return m_d; }int m_d;};int _tmain(int argc, _TCHAR* argv[]){Base *d0 = new Base;printf("Base *d0:\n");printf("d0.m_d = %d\n", d0->m_d);printf("d0.function.m_d = %d\n\n",d0->d_func());Base *d1 = new Derived;printf("Base *d1:\n");printf("d1.m_d = %d\n", d1->m_d);printf("d1.function.m_d = %d\n\n",d1->d_func());Derived *d2 = new Derived;printf("Derived *d2:\n");printf("d2.m_d = %d\n", d2->m_d);printf("d2.function.m_d = %d\n\n",d2->d_func());printf("delete d0:\n");delete d0;printf("\ndelete d1:\n");delete d1;printf("\ndelete d2:\n");delete d2;printf("\n");return 0;}


Console Output:

               

     Fig.01  Fig.02


                                                                                              


Memory Structure:


Fig.03


comment 1:

1. As shown in illustration Fig.03, object d1 has its m_d valued 100, while d2 200, which is because of the different statements for d1(Base *) and d2 (Derived *).

2. d2 has its parent mem part in which the m_d equals 100, while d2 also has m_d but valued 200, which touches the key point in this article: how c++ will deel with the 2 same named variable?

   child's variable will not overlaid its parent variable of the same name.


3. there is another question :  why here statements "virtual" key word to Base class ?

   The reason is that: when u declared a object like d1, u must assign "virtual" flag to its destructor... only doing like this, you could delete its pointed subclass mem part.

delete d0:

will directly call Base::~Base(); as shown in illustration Fig.01

delete d1 : 

 In case of "virtual" declared:  "delete d1" will first call Deried::~ Derived() and then Base::~Base()as shown in illustration Fig.01

 In case of "virtual" not declared:"delete d1" wil only call Base::~Base();as shown in illustration Fig.02

delete d2:  

       will first call Derived::~Derived() and then Base::~Base();as shown in illustration Fig.01


转载请标明出处,原文地址:http://blog.csdn.net/scorpiuseol/article/details/7425287

原创粉丝点击