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;
}
The pointer returned by
newgets implicitly converted tobool, which is then passed toMyClass(bool).In other words, the following:
is equivalent to:
Since the pointer returned by
newis never null, the conversion always yieldstrue, which is what gets passed tonumber3‘s constructor. The newly allocated pointer gets leaked.You probably meant to say:
(note the asterisks.)
You would not have had this problem if you declared the constructor
explicit:The code would fail to compile, which would immediate tell you that something was amiss.