Thread: somefunc(int& a = 4) -> default argument for ‘int& a’ has type ‘int’

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #5
    Registered User
    Join Date
    Feb 2006
    Posts
    312
    You can't have a reference to a literal value, therefore having a default argument for a reference doesn't make much sense.

    One thing you could do (I don't reccomend doing this because it involves global variables) is make your reference have a default variable to refer to
    Code:
    #include <iostream>
    
    int default_arg = 10;
    void foo(int& bar = default_arg)
    {
        std::cout << bar << std::endl;
    }
    
    int main()
    {
        int i = 5;
        foo(i);
        foo();
    }
    Or, you could just overload your functions (This is a much better solution)
    Code:
    #include <iostream>
    
    void foo(int& bar)
    {
        std::cout << bar << std::endl;
    }
    
    void foo()
    {
        std::cout << 10 << std::endl;
    }
    
    int main()
    {
        int i = 5;
        foo(i);
        foo();
    }
    Last edited by Bench82; 08-28-2007 at 01:57 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. pointer to array of objects of struct
    By undisputed007 in forum C++ Programming
    Replies: 12
    Last Post: 03-02-2004, 04:49 AM
  2. Erros in Utility Header File
    By silk.odyssey in forum C++ Programming
    Replies: 4
    Last Post: 12-22-2003, 06:17 AM
  3. header file bringing errors?
    By bluehead in forum Windows Programming
    Replies: 4
    Last Post: 08-19-2003, 12:51 PM
  4. Warnings, warnings, warnings?
    By spentdome in forum C Programming
    Replies: 25
    Last Post: 05-27-2002, 06:49 PM
  5. gcc problem
    By bjdea1 in forum Linux Programming
    Replies: 13
    Last Post: 04-29-2002, 06:51 PM