poninter to member error

What's wrong with that?
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
struct Foo
{
    Foo(int val = 9) : ptr(new int(val)) {}
    int * ptr;
};

int main()
{
    Foo* foo = new Foo ;
    std::cout << (foo->*ptr) ;
}


I get this compiler message:

error: ‘ptr’ was not declared in this scope
std::cout << (foo->*ptr)
(foo->*ptr)
Wrong syntax. Should be *(foo->ptr)
Last edited on
What about this?

https://en.cppreference.com/w/cpp/language/operator_member_access#Built-in_pointer-to-member_access_operators

Here it's the 'pointer to member of pointer' operation.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
struct Foo
{
    Foo(int val = 9) : ptr(new int(val)) {}
    int * ptr;
};

int main()
{
  Foo* foo = new Foo;

  Foo* foo2 = new Foo;
  *(foo2->ptr)=10;

  auto pointer_to_member = &Foo::ptr;
  std::cout << *(foo->*pointer_to_member)  << '\n';
  std::cout << *(foo2->*pointer_to_member) ;
}
Last edited on
Topic archived. No new replies allowed.