Constructor within a template

This is my first experiment with templates, and I'm a little confused. I'm writing a constructor and have this:

1
2
3
4
5
6
7
D_Node<Item>::D_Node( const Item &init_data = Item( ), 
			   D_Node *init_fore = NULL, D_Node *init_back = NULL )
    {
        data_field = init_data;
        link_fore = init_fore;
        link_back = init_back;
    }


However, this won't compile. I get the following error (actually, three of them, one for each variable:

default argument given for parameter 1 of 'my_namespace::D_Node<Item>::D_Node(const Item&, my_namespace::D_Node<Item>*, my_namespace::D_Node<Item>*)'

'after previous specification in 'my_namespace::D_Node<Item>::D_Node(const Item&, my_namespace::D_Node<Item>*, my_namespace::D_Node<Item>*)'


I think that I understand what the error message it telling me, but this is exactly how I have been taught to write this constructor (or at least how I THINK I've been taught...). What am I doing wrong?

Thanks.
Follow up: I found something on this error that says:

"This occurs when the implementation file (.cxx) specifies a default argument. Only header files (.h) should ever give a default value. "

I can make this go away by inlining the variable assignments within the header file. But I still don't understand this. Why can't I set these variables within the implementation file? That doesn't make any sense to me.

Thanks again.
closed account (DSLq5Di1)
It is to prevent you from redefining the default value, else you might have a declaration of foo(bar = 0) while in the implementation foo(bar = -1).
Last edited on
Thanks. What I don't understand is why this is different than any old default constructor. Say that I have a normal old class (not within a template) with private variable x. In my default constructor in the implementation file, I know that I can have a line that says x = 0;. So why is this any different? Is it something about templates?

Thanks again!
closed account (DSLq5Di1)
I see what you mean, but I'm not really sure why that is the case either. I've created a test case and opened a question over @stackoverflow, hopefully they can provide you with an answer. ^^

http://stackoverflow.com/questions/6805507/default-constructor-defined-with-default-arguments-outside-the-class-definition
Thanks!
Topic archived. No new replies allowed.