Groups    |     Jobs    |      User Space 

Hello, pls   log in or   register
current location:   up9rade > groups > Work MS
Question about pure virtual functions

20080424 10:51:01   from: Lorryastra1


Hi Freedo:

I think maybe I misunderstand the concept
of pure virtual function and abstract class when some classed inherit
from it. What I understand is: If a new class(concrete class, not abstract one)
inherits from an abstract class, it must define all of the pure virtual
functions, if not, then this new class has an error and we can justify this
error not until we define an object of this new class.

And what I can get the view of c++ compiler is : if a new class inherits
from an abstract class, new class doesn't need to define all of the pure
virtual functions, that's no problem, but you can't define an object of this
new class, if you define one, you are wrong.
Is that right?




example:



class Pet
{
public:
virtual void speak() const = 0;
virtual void eat() const = 0;
};

class Dog : public Pet {
public:
void eat() const {}
};



// if you write here, and then press F7, no error.



int main()

{

//! Dog d; that's an error.

}



// why compiler must wait to tell me errors until I've created an object.

// I think if I create the class dog and then compile it, the compiler should tell me the error, 'cos I don't override all of the pure virtual functions.



如果我说的不清楚可以用汉语交流一下, 我已经尝试在Microsoft的newsgroup里面讨论这个问题,基本上大家对我对于Compiler的看法表示漠视. Freedo我想听听你的意见。



因为我想如果继续从Dog继承下去,到Dog100(有点儿夸张)的时候(说明一下:从Dog1开始我会全部override Pet中的Pure virtual functions,虽然对于函数speak来讲我觉得应该叫做redefine而不是override了,因为Dog类里面没有实现),我去实现一个Dog100的对象,那么编译器告诉我没有实现Pet这个Abstract class的speak纯虚函数,那么我们是不是要花时间去寻找到底我们继承中哪个类出了问题呢? 虽然很快可以找到但是我仍然认为是很花时间的.



另外我认为继承到Dog这个类的时候,Dog类几乎已经没有任何用处:

1.如果我们利用它创建对象,肯定有编译问题。

2.如果我们让它作为Base class继续去inherit, 那么我觉得是会有更大的 potential error 在其中的。



Freedo,感谢你花时间看我的问题,我尝试过去Up9rade.com去贴这个问题,但是三次都没有成功,再次感谢。

------------------------------------------------------------------------------------------------------------


20080509 16:18:01:   Lorry Town    quote    
FreeDo,能帮我看看这个问题吗,好久了,谢谢
20080512 14:36:29:   freedo    quote    
Hi Lorry, 代为回答:

首先,关于你举的例子,很好很有趣 :)
A是基类,A1继承自A,A2, A3 一直下去直到A100
那么只有A100企图定义一个对象, 所以只有A100处报错了。 是有点问题。 但是一般的编译器都应该提出你少定义了基类的哪一个函数。

再者,A1继承的时候部实现A的所有纯虚函数,那么A1也算个接口类,而且不止A1,一直到A99都是接口类。

那么从这个角度,这个例子实用性不大了就。

所以,分两个方面:
1.纯虚函数必须在派生类中实现。 比如在A中定义了一个纯虚函数, 那么B中必须实现它才能定义B的instance。
2、编译器啥时候报错是编译器的事情。 它可以在你企图声明一个B的对象的时候再报错。他也可以把错误报到B的定义中

所以提醒是:
1、编译器的实现没有必要太死板,不要在意编译器在何处何时报错
2、纯虚函数是用来定义接口function的。 所以一般都在接口类(其他语言如java中有专门的interface关键字)。 按照用途来讲,就是定义接口的时候用,不要乱用一般

你的探索值得鼓励。从实用角度也应该考虑结合。 over.


I want to say something...

Input autho code, click on image to change another code: