Passing member variable as default arg to member function

This is a discussion on Passing member variable as default arg to member function within the C++ Programming forums, part of the General Programming Boards category; Is it possible to pass a member variable as the default argument to a function of the same class? I ...

  1. #1
    Registered User
    Join Date
    Mar 2009
    Posts
    399

    Passing member variable as default arg to member function

    Is it possible to pass a member variable as the default argument to a function of the same class? I want to reverse a linked list using recursion, but I need to pass the head of the linked list the first time that the function is called.

    Something like this but that actually compiles:
    Code:
    class Linked_List
    {
    private:
    	Tree_Node *head;
    public:
    	void reverse(Tree_Node *next = head);
    };

  2. #2
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,708
    No, but you can do this instead:

    Code:
    void reverse(Tree_Node *next = 0)
    {
        if(next == 0)
            next = head;
    // ...etc...
    }
    But a better approach is probably just to write a separate function:

    Code:
    void reverse(Tree_Node *next)
    {
    // ...etc...
    }
    
    inline void reverse(void)
    {
        reverse(head);
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 4
    Last Post: 05-13-2011, 08:28 AM
  2. Problem defining structure
    By MTK in forum C Programming
    Replies: 12
    Last Post: 09-08-2009, 03:26 PM
  3. passing to a member function by reference?
    By Terran in forum C++ Programming
    Replies: 8
    Last Post: 06-04-2008, 07:47 PM
  4. Replies: 3
    Last Post: 07-23-2006, 01:09 PM
  5. Replies: 28
    Last Post: 07-16-2006, 11:35 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21