Same named Variables In C++ inheritance

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值