0

In C++, I think it's not allowed to use non-static member variable in static method. However, what does this syntax mean? It compiles and runs.

class Bar {
 public:
  static void print() {
    // What does &Bar::val_ mean???
    cout << &Bar::val_ << endl;
  }

 private:
  int val_ = 123;

};

int main()
{
    Bar::print();
    return 0;
}

https://onlinegdb.com/BkjHR1FE8

Gerhardh
  • 11,688
  • 4
  • 17
  • 39
fmars
  • 139
  • 1
  • 4
  • 2
    Please take several weeks to read a good [C++ programming book](http://stroustrup.com/Programming/), then some [C++ tutorial](http://www.cplusplus.com/doc/tutorial/) then some [C++ reference](https://en.cppreference.com/w/cpp) then the [C++ standard](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf). It would take dozen of pages and of hours to explain you what a [pointer](https://en.wikipedia.org/wiki/Pointer_(computer_programming)) or an [offset](https://en.wikipedia.org/wiki/Offset_(computer_science)) is. And C++ is a very complex programming language. – Basile Starynkevitch Mar 01 '20 at 08:18
  • 3
    https://stackoverflow.com/questions/670734/pointer-to-class-data-member – Nikos C. Mar 01 '20 at 08:20
  • See https://norvig.com/21-days.html for more insights0 – Basile Starynkevitch Mar 01 '20 at 08:21
  • 1
    U're not using da variable but taking it's address (relative to the begin (first member) of da class). – J. Doe Mar 01 '20 at 08:21
  • 1
    @J.Doe Nope. There is no address for that variable since there's no object of type `Bar` anywhere. – Nikos C. Mar 01 '20 at 08:22
  • @NikosC. simplified to fit in a comment on SO. – J. Doe Mar 01 '20 at 08:23
  • Please don't use unrelated language tags. – Gerhardh Mar 01 '20 at 09:56
  • @NikosC. Thank you. Now it explains. – fmars Mar 03 '20 at 06:00

0 Answers0