Re: some puzzles
thomas <FreshThomas@gmail.com> wrote:
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?
There is none. At line 1, the 'virtual' keyword is optional.
2.why people sometimes define constructor/destructor virtual?
Nobody ever defines a constructor as virtual. Destructors are defined as
virtual so the base destructor will be called when a pointer to derived
is deleted.
what if a pure virtual constructor/destructor?
Destructors must be defined. You can have this:
class Foo {
public:
virtual ~Foo() = 0;
};
but you still have to define Foo::~Foo() somewhere. What the above does
is make the class abstract, even if all other member-functions are
defined.
3.
--code--
int *x = new int[0];
cout<<x<<endl;
--code--
the result is not 0, what happened?
'new' is guaranteed to return memory or throw. In the above, you newed a
block of memory of unspecified size, that can't be accessed for any
reason. "*x" would be undefined behavior.
4. when calling "delete []p;", how does the program know how many
elements should be destroyed?
How the system does unspecified by the language.