Re: [Dev-C++] Constructor and Destructor
Open Source C & C++ IDE for Windows
Brought to you by:
claplace
|
From: Per W. <pw...@ia...> - 2003-07-09 13:46:02
|
Nothing strange here... c->f() only works because:
1: A::f is not virtual, i.e. there is no need to lookup a function pointer
indirectly through the object. It is just a normal function call.
2: A::f() does not try to reference any dynamic data owned by the object.
In this case it calls a globally declared stream with a constant text
string. If it had tried to call a virtual method, or update any member
variables of the A class, it would have failed.
/Per W
On Wed, 9 Jul 2003, Avik Ghose wrote:
>
> Hi Lohit,
>
> look for my answers inline pls.
>
> "Verma, Lohit" <Loh...@hp...> wrote:
>
> Hi
> I have a question regarding constructors and destructors, and about class pointers
> If I have a class A (see below), Now the second call crashes
>
> Also I can call a member function without allocating memory for a class object.
>
> Please see code below and advice.
>
> Thanks a lot
>
> Lohit
>
>
>
> #include <iostream>
> using namespace std;
>
> class A{
>
> public:
> A(){
> delete this;
> }
> ~A(){
> cout<<"~A";
> }
>
> f(){
>
> cout<<"HELLO\n";
>
> }
>
> };
>
> int main()
> {
> A *a=new A();//works
>
> It works because you have alloated the object a from heap and the 'delete' operator works correctly in this case.
>
>
> A b;//crashes why?? how is it any different from above.
>
> This crashes beacuse a is allocated from stack or compile time memory, so any attempt to explicitly delete it will result in a crash.
>
> A *c;
>
> c->f();//works why when I have not allocated any memory for this.
>
> The third part got me stumped!!! I am attaching a code, the results are strange on devcpp!
>
> }
>
>
> DISCLAIMER: The information in this message is confidential and may be legally privileged. It is intended solely for the addressee. Access to this message by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, or distribution of the message, or any action or omission taken by you in reliance on it, is prohibited and may be unlawful. Please immediately contact the sender if you have received this message in error. Thank you.
>
>
>
>
> Thanx and Regards
> Avik Ghose
> SMS using the Yahoo! Messenger;Download latest version.
|