EverSpring working shop

To pursue creative ideas based on nature.

统计

留言簿(1)

他山之石

阅读排行榜

评论排行榜

Call Super Function in the Override function of the derived class

The derived class overrides the function in the base class. However, in some cases, we need to reuse the function of the base class in the overrided function. For C++, the scope operator is used to force a call to use a particular version of a overrided function.
Below is the example code, this code also contains the usage of the private inheritance.


#include "stdafx.h"

#include 
<iostream>
#include 
"stdio.h"
#include 
<string>
using namespace std;

class base 
{
public:
    
void basename()
    
{
        cout 
<< "this is base name\n";
    }

protected:
    
int i;
    
void base2ndname()
    
{
        cout
<<"this is base private name\n";
    }

}
;

class private_derived:private base  //private derivation, access control updates for the user of derivated class 
{
public:
    
void basename() //override the base function
    {
        cout 
<< "this is my derived name\n";
        
//basename();  // This will cause the endless loop
        this->base::basename();
    }
;
    
int use_base()
    
{
        
this->base::basename();  // use the scope operator to use the base class function
        this->base::base2ndname();
        basename();
        
return i;
    }

}
;

int _tmain(int argc, _TCHAR* argv[])
{
    base base_obj;
    private_derived derive_obj;

    cout 
<< derive_obj.use_base();

}

posted on 2007-10-21 18:07 everspring79 阅读(341) 评论(0)  编辑 收藏 引用 所属分类: Notes


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   博问   Chat2DB   管理