Question about constructor declaration with different arguments

Hi,

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...
if you're supplying a third parameter it'll use that one.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

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.
Last edited on
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" ??
so why even type "*parent = 0" ??

Because that is what tells the compiler the third argument is optional and what to use for a default value if the third argument is not supplied.

If the third argument was not optional, you would need two different constructors to allow calling the constructor with either two or three arguments.
1
2
3
4
// Two argument variant
my_class(int a, int b) 
// Three argument variant
my_class(int a, int b, my_class* parent) 





ah so it works! Thank's, I did not know that I have to explicitly define optional parameters with a default value..

Thank you!
Topic archived. No new replies allowed.