Search code examples
c++classdeclarationmember-functions

too few arguments in function call?


too few arguments in function call? what's wrong with this code? I want to output to std::cout day

#include <iostream>
#include <string>

class Date
{
public:
    Date(unsigned _day, unsigned _month, unsigned _year) : day(_day), month(_month), year(_year) {}
    int GetDate(Date& dt)
    {
        return dt.day;
    }
private:
    unsigned day, month, year;
};

int main()
{
    Date dt(07, 10, 2004);
    std::cout << dt.GetDate();

    return 0;
    std::cin.get();
}

i understand the principle but I don't know what to do

/*too few arguments in function call
    Error   C2660   'Date::GetDate': function does not take 0 arguments */

Solution

  • As this member function

    int GetDate(Date& dt)
    {
        return dt.day;
    }
    

    is a non-static member function then it is natural when it outputs the data member day of the object for which it is called. But it is defined with a parameter that accepts another object of the type Date.

    Thus in this call of the function

    std::cout << dt.GetDate();
    

    you need to specify an argument of the type Date like for example

    Date dt(07, 10, 2004);
    std::cout << dt.GetDate( dt );
    

    But this does not make a great sense.

    The function should be defined in the class like

    int & GetDate()
    {
        return day;
    }
    

    with its overload

    const int & GetDate() const
    {
        return day;
    }
    

    In this case this code snippet

    Date dt(07, 10, 2004);
    std::cout << dt.GetDate();
    

    will make a sense.

    Though it would be better to name the function as GetDay.

    Pay attention that this statement

    std::cin.get();
    

    does not have an effect because it is placed after the return statement. Maybe you mean

    std::cin.get();
    return 0;