开发者

virtual inheritance query

class开发者_运维问答 Base {  
public:  
  Base(){ }  
  virtual void Bfun1();  
  virtual void Bfun2();  
};  

class Derv : public Base {  
public:  
  Derv(){ }  
  void Dfun1();  
};  

Is there a difference between above definitions and the below ones ? Are they same ? if not how both are the different functionally ?

class Base { 
public:   
  Base(){ }  
  void Bfun1();  
  void Bfun2();  
};  

class Derv : public virtual Base {  
public:  
  Derv(){ }  
  void Dfun1();  
};  


They are completely different. The first set defines Bfun1 and Bfun2 as virtual function, that allows overriding them in the derived class and call those in the derived class through a base class pointer:

// assume you've overridden the functions in Derived
Base* base_ptr = new Derived;
base_ptr->Bfun1(); // will call function in derived

The second set, however, they're just normal functions. Instead, you declared the base class to be virtual, which has many implications you best read about in a good C++ book or search through the SO questions, I think we have one on that topic.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜