CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Jun 2015
    Posts
    175

    Default values for a user-defined types

    Hi all,

    Please consider this snipped-code:

    Code:
    int main()
    {
       cout << int() << endl;
       return 0;
    }
    This will usually result in showing 0 as the output.

    Consider that we have a user-defined type like this:

    Code:
    class myvals
    {
    public:
       myval() { };
       int x = 5;
       double y = 12.5;
    };

    Now consider a function that receives an int and a double as its arguments:

    Code:
    void foo(int i, double d) {
     cout << "i = " << i <<" and d = " << d << endl;
    }
    Now how to use the function foo this way:
    Code:
    foo(myvals());
    ?

  2. #2
    Join Date
    Jan 2006
    Location
    Singapore
    Posts
    6,765

    Re: Default values for a user-defined types

    Perhaps you just need to do some function overloading:
    Code:
    void foo(int i, double d) {
        cout << "i = " << i <<" and d = " << d << endl;
    }
    
    void foo(const myvals& vals) {
        foo(vals.x, vals.y);
    }
    Now this will work as expected:
    Code:
    foo(myvals());
    C + C++ Compiler: MinGW port of GCC
    Build + Version Control System: SCons + Bazaar

    Look up a C/C++ Reference and learn How To Ask Questions The Smart Way
    Kindly rate my posts if you found them useful

  3. #3
    Join Date
    Jun 2003
    Location
    Armenia, Yerevan
    Posts
    720

    Re: Default values for a user-defined types

    Another way is to instantiate the class's object and pass it to the function parameter.
    Code:
    #include <iostream>
    #include <string>
    
    class myvals
    {
    public:
       myvals() : x(5), y(12.4) {}
       int x;
       double y;
    };
    void foo(int i, double d) {
     std::cout << "i = " << i <<" and d = " << d << std::endl;
    }
    
    int main()
    {
      const myvals& ref = myvals();
      foo(ref.x, ref.y);
    }

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured