Home > Software engineering >  Class initialization fails with default constructor
Class initialization fails with default constructor

Time:03-19

I am learning about classes in C and I created a simple one that just creates an interval from int a to int b, using a dynamic int array. Here's the code:

Interval::Interval() {
    a_ = 0;
    b_ = 0;
    interval = new int[2];
    for (int i = 0; i <= 1;   i) {
        interval[i] = 0;
    }
}

Interval::Interval(int a, int b) {
    if (a > b) Interval(); // doesn't seem to work?

    else if (a == b) {
        a_ = a;
        b_ = b;
        interval = new int[2];
        for (int i = 0; i <= 1;   i) {
            interval[i] = a;
        }
    } else {
        a_ = a;
        b_ = b;
        int size = b - a   1;
        interval = new int[size]; 
        for (int i = 0; i < size;   i) {
            interval[i] = a  ;
        }
    }
}

Interval::~Interval() {
    delete[] interval;
    cout << "Destructed\n";
}

However, on this part here:

if (a > b) Interval();

It doesn't seem to create it. Where am I wrong?

CodePudding user response:

Noting that your default constructor is equivalent to Interval(0,0), you can reuse the non-default constructor instead, by forwarding to it:

Interval::Interval() : Interval(0,0) {}


Interval::Interval(int a, int b) 
    : a_(a <= b ? a : 0),
      b_(a <= b ? b : 0)
 {
    if (a_ == b_) {
        interval = new int[2] {a_, a_};
    } else {
        int size = b_ - a_   1;
        interval = new int[size]; 
        for (int i = 0; i < size;   i) {
            interval[i] = a_   i;
        }
    }
}

CodePudding user response:

This line

if (a > b) Interval();

when the condition is met, it default constructs a temporary Interval which is destroyed at the end of the line.

Your code looks rather compilcated for what it does. The array should rather be a std::vector such that you need not mess around with manual memory allocations. Anyhow, to get what you want "I want default constructed object in that case." the easy fix is the following:

if (a > b) {
    a = 0;
    b = 0;
}

if (a == b) {
    a_ = a;
    b_ = b;
    interval = new int[2];
    for (int i = 0; i <= 1;   i) {
        interval[i] = a;
    }
} else { ...
  • Related