Home     |     .Net Programming    |     cSharp Home    |     Sql Server Home    |     Javascript / Client Side Development     |     Ajax Programming

Ruby on Rails Development     |     Perl Programming     |     C Programming Language     |     C++ Programming     |     IT Jobs

Python Programming Language     |     Laptop Suggestions?    |     TCL Scripting     |     Fortran Programming     |     Scheme Programming Language


 
 
Cervo Technologies
The Right Source to Outsource

MS Dynamics CRM 3.0

C++ Programming

Using destructor


I have this class:

class MyArray {
public:
        MyArray(int a) : data(new int[a]){}

        ~MyArray() {delete[] data;}

        int& operator()(int a){
                return data[a];
        }

        int operator()(int a) const{
                return data[a];
        }

private:
        int* data;

};

int main() {

        MyArray myarr(5);
return 0;

}

But when are the destructor called?

The destructor is called implicitly when the object is distroyed - how
it is destroyed does not matter.

When "myarr" goes out of scope.
On May 28, 10:05 am, desktop <f@sss.com> wrote:

> I have this class:

> class MyArray {
> public:
>         MyArray(int a) : data(new int[a]){}

          MyArray(const int a) : data(new int[a]) { }

The destructor is invoked when the object goes out of scope. In this
case it happens when main returns. Add an output (std::cout <<
"~MyArray()";) to your d~tor to see it.

Did you mean to write int& MyArray::operator[](int a) { ... } ?

On May 28, 6:11 pm, Devon Null <theronnights@xgmailx.com> wrote:

btw, you can invoke destructor explicitly:
myarr.~MyArr();
note: in member functions you should write 'this->~MyArray();'. not
'~MyArray()' (without 'this->')

Note however that this is almost never a good idea.
On May 28, 3:02 pm, archimed7592 <archimed7@gmail.com> wrote:

and you can also jump off a skyscraper without a parachute.

> myarr.~MyArr();
> note: in member functions you should write 'this->~MyArray();'. not
> '~MyArray()' (without 'this->')

If a user of the class needs to manage the lifetime of an object, he/
she should be doing it through dynamic allocation using smart pointers
or new/delete.

"desktop" <f@sss.com> wrote in message

news:f3enk0$jgs$1@news.net.uni-c.dk...

Here is where the destructor is called.   This return statement is exiting
the function main, myarr goes out of scope, so it's destructor is called.

Add to del.icio.us | Digg this | Stumble it | Powered by Megasolutions Inc