Syntax question

This is a discussion on Syntax question within the C++ Programming forums, part of the General Programming Boards category; Here is some code I've read which overloads the new operator for a class, I have a couple of syntax ...

  1. #1
    Registered User Stonehambey's Avatar
    Join Date
    Jan 2008
    Location
    Kent, UK
    Posts
    118

    Syntax question

    Here is some code I've read which overloads the new operator for a class, I have a couple of syntax questions about it

    Code:
    void *three_d::operator new[](size_t size)
    {
      void *p;
      cout << "Allocating array of three_d objects.\n";
      // throw an exception on failure
      p = malloc(size);
      if(!p) {
        bad_alloc ba;
        throw ba;
      }
      return p;
    }
    Now new returns a memory address (I believe) so is void* what a function must return if it is to return that?

    Also, this is overloading new to allocate memory for an array of objects, but I don't see how the code would change if we were to simply overload new normally?

    Sorry if these questions seem a little trivial, but they've been bugging me for a couple of days now

    Stonehambey

  2. #2
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Yes, void * is the right return for new. It is identical for new [] and new - it's no difference to the memory allocation itself, only the calling of the constructor(s).

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  3. #3
    Registered User Stonehambey's Avatar
    Join Date
    Jan 2008
    Location
    Kent, UK
    Posts
    118

    Thumbs up

    Thanks

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Syntax question: &(++x)
    By yoshiznit123 in forum C Programming
    Replies: 8
    Last Post: 06-02-2006, 10:40 PM
  2. using c++ in c code
    By hannibar in forum C Programming
    Replies: 17
    Last Post: 10-28-2005, 09:09 PM
  3. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 06:39 AM
  4. Learning OpenGL
    By HQSneaker in forum C++ Programming
    Replies: 7
    Last Post: 08-06-2004, 08:57 AM
  5. pointer to array of objects of struct
    By undisputed007 in forum C++ Programming
    Replies: 12
    Last Post: 03-02-2004, 03:49 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21