using member data as default argument

Discussion in 'C++' started by hall, Dec 10, 2003.

  1. hall

    hall Guest

    Hi.
    I'd like to use a data member as a default argument to a member
    function, something like this:

    class A{
    public:
    int data;

    A(): data(0) { };

    fun(int arg=data){ /*function body*/ };
    };

    The code above will not compile (my borlad compiler says: member A::data
    cannot be used without an object), but is there a way to achieve this
    (without too much code and too much impact on speed of execution)?

    regards
    hall


    --
    ( - Remove capital X from email to reply - )
    hall, Dec 10, 2003
    #1
    1. Advertising

  2. hall

    tom_usenet Guest

    On Wed, 10 Dec 2003 14:05:39 +0100, hall <>
    wrote:

    >Hi.
    >I'd like to use a data member as a default argument to a member
    >function, something like this:
    >
    >class A{
    >public:
    > int data;
    >
    > A(): data(0) { };
    >
    > fun(int arg=data){ /*function body*/ };
    >};
    >
    >The code above will not compile (my borlad compiler says: member A::data
    >cannot be used without an object), but is there a way to achieve this
    >(without too much code and too much impact on speed of execution)?


    Sure:

    void fun(int arg){ /*function body*/ }
    void fun() {fun(data);}

    You can't access the "this" pointer for a default argument, so the
    above is the best you can do. It should have no impact on speed,
    thanks to inlining (just make sure the forwarding version is inline).

    Tom

    C++ FAQ: http://www.parashift.com/c -faq-lite/
    C FAQ: http://www.eskimo.com/~scs/C-faq/top.html
    tom_usenet, Dec 10, 2003
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Gert  Van den Eynde
    Replies:
    8
    Views:
    631
    Keith H Duggar
    Jan 26, 2004
  2. Mike Alexeev
    Replies:
    6
    Views:
    494
    Rob Williscroft
    May 23, 2004
  3. Replies:
    3
    Views:
    284
  4. Divick
    Replies:
    29
    Views:
    852
    Francesco S. Carta
    Sep 30, 2009
  5. Dwight Army of Champions

    class data member or member function argument?

    Dwight Army of Champions, Feb 21, 2010, in forum: C++
    Replies:
    4
    Views:
    1,539
    tonydee
    Feb 22, 2010
Loading...

Share This Page