20-CS-122-001 Computer Science II Spring 2012
Question

Virtual functions, classes, inheritance, lists, queues, stacks, applications

What's the deal with new?


Question:
    I have a question pertaining to the "new" keyword/operator in C++ and how it works. My background is in Java and VB.Net so this may be a dumb question. In C++ to create a new object you just simply declare and initialize the variable using only the constructor without using the new keyword. Is this the same as declaring and initializing a pointer of a type then use the "new" operator and then the constructor?

I'm sorry if I worded that confusing. Simply put does this:

  int a = 5; cout << a;
or this:
  int a(5); cout << a;
do the same as this?:
  int* a = new int(5); cout << *a;
From what I have learned on my own, is that they are in fact doing the same thing except in my 3rd example I am only creating the pointer and not directly referencing the value like I do in the first two examples. When would it be more favoured the use the 3rd example using pointers rather than the values? Wouldn't it always be best to use that 3rd example in case an exception is thrown so you can catch it? I have also read a little bit about how since 'new' creates a dynamic memory allocation and created from/in the heap unlike the other two examples which uses the stack because of the copy initialization? I'm not sure

Answer:
    C++ has confused newbies for decades because it admits several different ways to do things. People are afraid of pointers because they do not know when to use a * or & or when not to in C++. Java has nothing but pointers and there is no confusion. My programming style (the one I will use consistently in class) is to follow java convention. So, I will do things like this:
  #include <iostream>
  using namespace std;
	 
  int main () {
     int **a = new int*[10];
     for (int i=0 ; i < 10 ; i++) a[i] = new int(i);
     for (int i=0 ; i < 10 ; i++) cout << *a[i] << " ";
     cout << "\n";
  }
whose counterpart in java looks like this:
  public class a {
     public static void main (String args[]) {
        Integer a[] = new Integer[10];
        for (int i=0 ; i < 10 ; i++) a[i] = new Integer(i);
        for (int i=0 ; i < 10 ; i++) System.out.print(a[i]+" ");
        System.out.println();
     }
  }
Pretty funny, eh?

Continuing... the constructor is called in both languages. The new operator (which can be overloaded in c++!!!) gets some space from the OS and assigns the address of that space to a pointer variable (or else you lose it) through the = operator. In C++, once you grab space using 'new' it is your responsibility to free it when you do not need it - in java this is done automatically via a garbage collector. Hence, the destructor becomes important because a class may have used new internally and the space used by such objects must be freed.

To answer your question about the difference between a = 5 and int *a = new int(5) try this:

  #include <stdlib.h>
  #include <iostream>
  using namespace std;
		
  int main () {
     int *a = new int(5);
     free(a);
     int *b = new int(10);
     cout << *a << "\n";
  }
Pretty different, eh?

BTW this cannot happen in java because the reference to new Integer(5) persists through 'a' so the space is not freed when b is set to new Integer(10).

Check out the sources for the linux OS - they are in C, are freely available, and are from many authors. Pointers are used all over the place, especially pointers to functions. I prefer to use nothing but pointers like Java, although it is a slight pain to manage the destructors. Unfortunately, textbook authors think that * and & are too deep for the innocent minds of newbies so they stay away from them in many cases where they should not. I believe that if you show newbie students one way only, there will be no confusion. However, I will have a parameter passing lecture where we talk about all the ways C++ can represent objects.

Correct about exceptions.

Correct about the 1st examples existing in the stack - so they disappear automatically when execution continues out of their scope.