deallocating memory with delete

Posted on 2004-11-23
Last Modified: 2010-04-01
Code snipet:
class foo {
         foo() {var=new double [1000];}
         ~foo() {delete [] var;}
         double * var;
int main() {
         foo *a;
         a = new foo;
         delete [] foo;
         return 0;

I know that the memory allocated to the pointer "a" is released by delete, but what about "var" does the compile automatically know to release it since it is inside the class or do I need to do it.
Question by:BigLobowski
    LVL 5

    Expert Comment

    Hi BigLobowski,

    You need to change "delete[] foo" to "delete foo" as it was created with "new" and not "new ... [...]"

    When you delete a, it calls the destructor of a which in turn deletes var.
    LVL 8

    Accepted Solution

    hi there,

    you need to delete the object not the class.

    delete [] foo;

    should be

    delete a;

    also, when you delete "a", the destructor of "a" will be called before "a" is deallocated.  that is where you need to delete "var", as you have correctly.

    LVL 5

    Expert Comment

    Oops. Should've spotted that bit. It's clearly past my bedtime.
    LVL 8

    Expert Comment

    no worries.  those late nights will get the best of anyone.

    Featured Post

    How your wiki can always stay up-to-date

    Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
    - Increase transparency
    - Onboard new hires faster
    - Access from mobile/offline

    Join & Write a Comment

      Included as part of the C++ Standard Template Library (STL) is a collection of generic containers. Each of these containers serves a different purpose and has different pros and cons. It is often difficult to decide which container to use and …
    Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
    The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…
    The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.

    729 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    20 Experts available now in Live!

    Get 1:1 Help Now