I've got a question, I do not really understand what happens when I declare a constructor like this:
1 2 3 4
class my_class
{
my_class(int a, int b, parent* = 0);
}
When I now create a new instance of my_class with only two integers, then I know that third argument will be set to NULL doesn't matter if it was defined in the declaration (like it is here) or not.
But when I call the constructor like this:
1 2
my_class* test;
my_class test2(2,4, test);
What will happen then? Will g++ ignore the third parameter or will it give test a higher priority or not? I do not really know the priority of declaration/definition of function arguments...
class my_class
{
public:
my_class() {}
my_class(int a, int b, my_class* parent = nullptr) {
m_a = a;
m_b = b;
m_my_class = parent;
}
private:
int m_a;
int m_b;
my_class* m_my_class;
};
int main()
{
my_class* test = new my_class(9,10);
my_class test2(2, 4, test);
// test will contain 9, 10 and a null pointer
// test 2 will contain 2, 4 and a my_class object (i.e. "test")
return 0;
}
You could have tried this yourself and stepped through it with a debugger.
Ok& but then I'm asking myself when do I need to declare a constructor with a predefined argument like in this example? I mean, when I don't call the constructor with a third argument, *parent will always be NULL and when I call constructor with three arguments, *parent will be set to third argument... so why even type "*parent = 0" ??