In the below code I am trying to call a constructor of another Class in MyClass constructor. Its working fine.
But my question is this a right way to do it or assign with Initializer list.
1 2 3 4 5 6 7 8 9 10 11 12 13
class MyClass
{
AnotherClass* var;
public:
MyClass()
{
var = new AnotherClass(); // IS this Valid
}
~MyClass()
{
delete var;
}
}
The above code can't compile since var is not a pointer (lines 7 and 11 should be compile errors).
If "var" is simply an instance of AnotherClass and not a pointer, then the correct way (and
technically the only way) to initialize is through the initializer list.
(Note that C++ makes a distinction between "initializing" and "assigning" that most average
incorrectly programmers ignore.)