Re: some puzzles
thomas <FreshThomas@gmail.com> writes:
1.
---code--
class base{
public:
virtual void func();
};
class derive:public base{
virtual void func(); //1
};
---code--
As we know that Line 1 implements the function overloading,
what's the difference between "virtual void func();" and "void
func();" in L1?
That's the same difference as with 'final' methods in java.
2.why people sometimes define constructor/destructor virtual?
what if a pure virtual constructor/destructor?
constructor can't be defined as virtual AFAIK. destructurs must be
defined as virtual as soon as there is a virtual method, to allow
calling the right destructor (that is, the one of the exact class of
the object), when delete is called with a pointer to the object typed
as a superclass:
class A {
ResourceA* ra;
A(){ra=ra_alloc();}
virtual ~A(){
ra_free(ra);
}
};
class B {
ResourceB* rb
B(){rb=rb_alloc();}
virtual ~B(){
rb_free(rb);
}
};
int main(){
A* obj=new B();
delete obj; // <-- we want ~B to be called too here!
return 0;
}
3.
--code--
int *x = new int[0];
cout<<x<<endl;
--code--
the result is not 0, what happened?
There is only one null pointer.
4. when calling "delete []p;", how does the program know how many
elements should be destroyed?
new[] stores the size allocated in the allocated memory block.
Since these are probably homework, you won't have learned anything,
and be sure that any employer will detect it in the first five minute
of the interview. You probably won't get a job in C++ programming...
Next time, do your own homework!
--
__Pascal Bourguignon__