致开

C++ Common knowledge base

1. Derived classes use the function name to hide the function with the same names in Parent class. This is declared by C++ Language Specification. Actually this is not a good design, so we should try to prevent this happen in our design.

2. Override your "new" operator for your class if necessary. And keep in mind that the overrided "new" operation applies for whole inheritance tree.
class X
{
public:
  
void* operator new(size_t sz); //allocate sz bytes
  void  operator delete(void* p) //free p;
};

3. Inheritance talk.
As we know, you can call the child method through your base class or reference. But you could not call the child method through your base object even this method is overridden in your child class.
Say we have such a piece of code:
class Base
{
public:
    
virtual void Display(){
    cout
<<"base"<<endl;}
};

class Derived : public Base
{
public:
    
virtual void Display(){
    cout
<<"derived"<<endl;};
};
int _tmain(int argc, _TCHAR* argv[])
{
    Base ba;
    Derived de;
    ba 
= de;
    ba.Display();


    Base 
* pba = &de;
    pba
->Display();
    
return 0;
}
Many persons wonder this phenomenon and has a lot of questions. But if you take a look at the assembly code, you can get it clear.
//Base::Display actually is a global function. 
//In Compiling phase, this piece of calling will be regarded as calling the global function.
ba.Display();
0041155A  lea         ecx,[ba] 
0041155D  call        Base::Display (411140h) 

//As we know, the virtual methods in C++ are implemented by virtual table. 
//So this calling will be happen in execution time, which finds the correct method.
pba->Display();
00411568  mov         eax,dword ptr [pba] 
0041156B  mov         edx,dword ptr [eax] 
0041156D  mov         esi,esp 
0041156F  mov         ecx,dword ptr [pba] 
00411572  mov         eax,dword ptr [edx] 
00411574  call        eax  
00411576  cmp         esi,esp 
00411578  call        @ILT+455(__RTC_CheckEsp) (4111CCh) 


posted on 2009-01-04 16:42 Xiaxi 阅读(468) 评论(1)  编辑 收藏 引用

评论

# re: C++ Common knowledge base[未登录] 2009-01-04 22:24 908971

谢谢分享  回复  更多评论   


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


<2009年1月>
28293031123
45678910
11121314151617
18192021222324
25262728293031
1234567

导航

统计

常用链接

留言簿(1)

随笔档案

文章分类

文章档案

搜索

最新评论

阅读排行榜

评论排行榜