Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ one argument boolean constructor and "new" keyword: Logic Error

I have the following class in c++

class MyClass {

public:
  bool flag;

  MyClass (bool flag = false) {
    this->flag = flag;
  }
...
};

In my main (used for testing) I have something like so

int main() {
 MyClass number1 = MyClass(true);
 MyClass number2 = MyClass(false);
 MyClass number3 = new MyClass(false);
 MyClass number4 = new MyClass(true);
 MyClass number5 = new MyClass();
 std::cout << number1.flag << number2.flag << std::endl;
 std::cout << number3.flag << number4. flag << number5.flag << std::endl;
}

And my output (imagine boolean outputs true or false and the output is formatted better)

true, false 
true, true, true

The problem is when I use the "new" keyword to make a "MyClass" object it will always set the flag variable to true regardless of what I do or don't put into the argument constructor.

It works for the constructors not using "new" but not the ones using it. The only real difference I know between using and not using the keyword new is that if you don't use it, the variable is created on the stack, otherwise it is created on the heap. I don't see any way this could keep coming up wrong.

What would need to change if I wanted it to work properly? I do have other methods in the class that can successfully modify the flag variable, but initializing it doesn't work. I also tried using the member initialization list to construct the variable but that doesn't work either.

Thanks for your help!

Edit: Here is the code that does compile. I have two files, Test.c++ and AbstractCell.h. AbstractCell is MyClass and when this code runs it outputs "isAlive: 1"

 void test_abstract_2(){
   AbstractCell one = new AbstractCell();

      std::cout << std::endl <<  "isAlive:  " << one.alive << std::endl;

  }
like image 652
user1348913 Avatar asked Apr 27 '26 20:04

user1348913


1 Answers

The pointer returned by new gets implicitly converted to bool, which is then passed to MyClass(bool).

In other words, the following:

MyClass number3 = new MyClass(false);

is equivalent to:

MyClass number3(bool(new MyClass(false)));

Since the pointer returned by new is never null, the conversion always yields true, which is what gets passed to number3's constructor. The newly allocated pointer gets leaked.

You probably meant to say:

 MyClass* number3 = new MyClass(false);
 MyClass* number4 = new MyClass(true);
 MyClass* number5 = new MyClass();

(note the asterisks.)

You would not have had this problem if you declared the constructor explicit:

  explicit MyClass (bool flag = false) {
    this->flag = flag;
  }

The code would fail to compile, which would immediate tell you that something was amiss.

like image 73
NPE Avatar answered Apr 30 '26 10:04

NPE