0

I tried this and error was

error: invalid use of non-static data member 'A::n'

Why cant we assign data member in method?

#include <iostream>
using namespace std;
class A
{
    int n,m;
    public:
        A()
        {
           n=5;
           m=8;
        }
        void fun(int a,int b=n)
        {
            while(b--)
            {
                cout<<"XYZ";
            }
        }
};
int main()
{
    A obj;
    obj.fun(6);
    return 0;
}
Sachin
  • 55
  • 1
  • 5
  • The reason why is because the C++ language standard prohibits it. – paddy Oct 29 '20 at 10:10
  • Regarding `temp == 0` -- you should not do this, ever. Use `!temp`, or `temp == nullptr` or `temp == NULL`. – paddy Oct 29 '20 at 10:12
  • @Biffen it is data member in class which is defined(I have mentioned it above). I have just pasted a part of which. – Sachin Oct 29 '20 at 10:14
  • 1
    @paddy is there any reason why it is prohibited? Ohk I will keep that in mind about temp. – Sachin Oct 29 '20 at 10:17
  • @Biffen this is the complete code. I have created the instance also. https://ide.geeksforgeeks.org/DklDK4hJxT – Sachin Oct 29 '20 at 10:19
  • @Biffen I am sorry if i created some confusion(I tried to keep it very up to the point) Class A { int n,m; public: A() { n=5; m=8; } fun(int a,int b=n) { while(b--) { cout<<"XYZ"; } } } why it is throwing error " invalid use of non-static data member " when we call method fun with 1 parameter – Sachin Oct 29 '20 at 10:27
  • @biffen ohk i will add all the errors – Sachin Oct 29 '20 at 10:34
  • 1
    Does this answer your question? [How to use a member variable as a default argument in C++?](https://stackoverflow.com/questions/9286533/how-to-use-a-member-variable-as-a-default-argument-in-c) – Biffen Oct 29 '20 at 10:35
  • @biffen yes it is method overloading but i asked that why we can't assign data members? why it is prohibited is there some reason? – Sachin Oct 29 '20 at 10:42
  • @Sachin -- `temp == 0` is not forbidden by the language definition, just by some peoples' notions of good style. Its meaning is well defined. `0` is a null pointer constant, and comparing a pointer variable to 0 is just testing whether the variable holds a null pointer. – Pete Becker Oct 29 '20 at 13:49

1 Answers1

0

The default value of a function is supplied by the compiler, so at compile time. At compile time the compiler can't know the runtime value of your variable. This is why it doesn't work.

https://www.geeksforgeeks.org/default-arguments-c/

hechth
  • 95
  • 11