Click here to Skip to main content
15,885,278 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have the following program that works fine but I want to know if I can replace just the following line that use the " new operator " NumDays *days = new NumDays();
with another easier compatible C++ command.

I am asking this question because this resemble more to me a Java command than a C++

C++
int main() {
    NumDays *days = new NumDays();
    double hours;
    cout << "Enter numberof hours worked and get working days.\n";
    cout<< "Enter 0 to terminate the sequence. \n";


    while (true) {
        cout << "Enter number of hours" << endl;
        cin >> hours;

        if (hours < 0) {
            cout << "Invalid input. Please try again." << endl;
            continue;
        }
        if (hours == 0) {
            cout << "Exiting..." <<endl;
            break;
        }
        days->setWorkingHours(hours);
        cout << hours << " working hours is " << days->getDays() << " working days." << endl;
Posted
Updated 18-Sep-14 3:48am
v2
Comments
CPallini 18-Sep-14 11:05am    
Please note you should always release dynamically allocated memory (using delete).
Legor 19-Sep-14 3:37am    
The new command is perfectly valid C++. Also what do you mean with "easier" command. What isn't easy about using new to create an object?

1 solution

You could allocate the NumDays variable on the stack;
C++
NumDays days;

That would also mean you would have to change the way you reference methods on days;
C++
days->setWorkingHours(hours);

becomes
C++
days.setWorkingHours(hours);

Hope this helps
Fredrik
 
Share this answer
 
Comments
Yvan Rodrigues 18-Sep-14 10:19am    
Agreed. The only reason that I can think of to allocate this variable from the heap would be if it was quite big. Depending on the operating system, hardware, and compiler options, perhaps the stack is only 4096B and sizeof(NumDays) == 1024, it might make sense to allocate large items on the heap.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900