Use of new in CPP

Hi,

I wanted to know about the use of "new" in CPP;
Please consider the following program:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class ITEMS
{

    string name;

    public:
    void putString(string n)
    {
        name = n;
    }

    void getString()
    {
        cout << " Name is " << name << endl;
    }
};

int main()
{
    ITEMS a;
    ITEMS b = new ITEMS(); // Error here

    a.putString("Michael");
    a.getString();

    b.putString("Angelo");
    b.getString();

    return 0;
}


Could someone please tell me why would this give error?

Thank you.
You don't strictly need the () on that line. Remove them.
I am sorry but removing () still gives an error.
As in,
 
ITEMS b = new ITEMS; 


gives an error.
The new operator is for creating objects from the free-store rather than on the stack. These objects need to be accessed through a pointer:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class ITEMS
{

    string name;

    public:
    void putString(string n)
    {
        name = n;
    }

    void getString()
    {
        cout << " Name is " << name << endl;
    }
};

int main()
{
    ITEMS a;
    ITEMS* b = new ITEMS; // Use * to indicate a pointer

    a.putString("Michael");
    a.getString();

    b->putString("Angelo");
    b->getString();

    delete b; // remember to delete everything that you new

    return 0;
}
Last edited on
Thank you. It worked.
Just an addon question:
for better memory management, which way is prefered (declaring as a or b) ?
the "ITEMS a; " line will simply allocate the data
the "ITEMS b; " line will allocate the data, AND a pointer to it.

So theoretically speaking, declaring as 'a' will save you 4 bytes of memory. It really just comes down to preference.

Correct me if I'm wrong.....
Normally you should avoid using raw pointers, so a is generally preferred. However, sometimes you need to be able to create objects dynamically and so you have to use b. I think experience and practice will tell you when each method is most appropriate. Essentially it has to do with how long the object is expected to live.

Objects created like a, are destroyed automatically when they go out of scope, whereas objects created like b will live beyond the scope of their creation.
Always prefer method a. With method a, the object is created on the stack which is generally faster, its memory is automatically handled unlike the other more error-prone approach, and it is exception safe.

Use method b, only when you have to, and even then a smart pointer should be preferred over a raw one.
Topic archived. No new replies allowed.