yuqli
yuqli

Reputation: 5161

"new" does not call the specified constructor in a class?

There must be some flaws in my understandings about new operator.

Here is the relevant part of the code:

#include <queue>

using namespace std;

class MovingAverage {
public:
    /** Initialize your data structure here. */
    MovingAverage(int size) {
        queue<double> q;
        int max_size = size;
        int curr_size = 0;
        double sum = 0.0;
    }

private:
    queue<double> q;
    int curr_size;
    int max_size;
    double sum;
};

int main(){
    MovingAverage * m = new MovingAverage(3);  // This line does not work as expected!
    return 0;
}

In the above code, the class MovingAverage has a constructor MovingAverage(int size) that sets two of its member variables curr_size and sum to zero.

However, the line MovingAverage * m = new MovingAverage(3); in the main function does not return a pointer to an instance of the class with the two member curr_size and sumto zero.

Instead, the debugger shows the created object has curr_size = 1953853300 and max_size = 6647401.

enter image description here

How can I make the new operator calls the constructor I wrote?

Upvotes: 1

Views: 89

Answers (1)

HugoTeixeira
HugoTeixeira

Reputation: 4884

Your code is declaring local variables inside the constructor's body. The right approach is to use the constructor's member initializer list:

MovingAverage(int size):
    max_size(size),
    curr_size(0),
    sum(0.0)
{}

Besides that, ideally you shouldn't be using raw pointers like that. There are smart pointer classes like std::unique_ptr and std::shared_ptr that can make the code safer and easier to maintain. So your code could be:

#include <memory>

...
auto m = std::make_unique<MovingAverage>(3);

or

auto m = std::make_shared<MovingAverage>(3);

Upvotes: 3

Related Questions