-1

I'd like to pass a class's variable as a parameter to one of that class's methods, but I get an error that says "A reference to a non-static member must be relative to a specific object".

class myClass
{
private:
  int x = 1;
public:
  void func(int pos = x)
  {
    //whatever
  }
};

I'd like to make it so that if a parameter is passed when the method is called then that's the one used to initialize pos, otherwise x is used.

I tried looking for solutions but wasn't able to find anything. Any help is really appreciated.

me myself
  • 23
  • 4
  • 1
    Overloads: One taking one (non-default) argument; One taking no arguments, calling the first and passing `x`. – Some programmer dude Apr 12 '23 at 13:00
  • 1
    To receive a good solution you should explain: Why you need this. IMO best solution is to drop default value and provide an overload. – Marek R Apr 12 '23 at 13:08
  • Refer to [how to ask](https://stackoverflow.com/help/how-to-ask) where the first step is to search and then research and you'll find plenty of related SO posts for this. – Jason Apr 12 '23 at 13:21

2 Answers2

2

As the comment suggest, you can do function overloading. Define one function taking one parameter and one taking no parameters, calling the first and passing the class's variable, in this case, x.

It would look like this:

#include <iostream>

class myClass
{
private:
    int x = 1;
public:
    void func(int pos)
    {
        std::cout << pos;
    }
    void func()
    {
        func(x);
    }
};
int main()
{
    myClass my_class;
    my_class.func(); // no parameters 
    std::cout << '\n';
    my_class.func(2); // one parameter
}

The program prints:

1
2

Link.

0

In C++ you cannot use a non-static member as a default parameter.

You probably want this:

class myClass
{
private:
  static int x;
public:
  void func(int pos = x)
  {
    //whatever
  }
};

int myClass::x = 1;

or this:

class myClass
{
private:
  int x = 1;
public:
  void func(int pos)
  {
    //whatever
  }

  void func()
  {
    int y = x;
    // whatever
  }
};
Jabberwocky
  • 48,281
  • 17
  • 65
  • 115