CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5
  1. #1
    Join Date
    Mar 2002
    Posts
    55

    delete class question

    Hi, if I have a class A

    class A
    {
    public:
    char *pchar;
    };

    A *pA;

    int main()
    {
    pA = new A[4];
    pA[0].pchar = new char[256];

    delete[] A;
    return 0;
    }

    is that good enough?
    Or do I have to explicitly delete pchar?

  2. #2
    Join Date
    Sep 2001
    Location
    San Diego
    Posts
    2,147
    You have to explicitly call

    delete [] pA[0].pchar

    Hope this helps,

    - Nigel

  3. #3
    Join Date
    Jan 2001
    Posts
    588
    This is a place where a destructor would be in order. Your A class would become:

    class A
    {
    public:
    A();
    ~A();
    char *pchar;
    };

    A::~A()
    {
    if (pchar != NULL) delete pchar;
    }


    Or, if pchar would be pointing to the beginning of a string (a character array), it would be delete [] pchar. Anyway, you get the idea. When an A object goes out of scope, the destructor (~A) will be called, which in this case will deallocate the memory that pchar points to. Hope this helps.

  4. #4
    Join Date
    Mar 2002
    Posts
    55
    thx Bob, works perfectly.

  5. #5
    Join Date
    Apr 1999
    Location
    Altrincham, England
    Posts
    4,470
    One thing to note, though: you can't (or at least shouldn't) mix new with delete[] or new[] with delete. Since you have no way of enforcing one form of new over another (because of the public data member), you lay yourself open to some hard-to-find bugs. It would be much better to make the data member private and use public member functions to do the allocation - that way you control which form of new/delete you use.

    Or, even better, use std::string, not char*.
    Correct is better than fast. Simple is better than complex. Clear is better than cute. Safe is better than insecure.
    --
    Sutter and Alexandrescu, C++ Coding Standards

    Programs must be written for people to read, and only incidentally for machines to execute.

    --
    Harold Abelson and Gerald Jay Sussman

    The cheapest, fastest and most reliable components of a computer system are those that aren't there.
    -- Gordon Bell


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured