1

I have a simple structure and I want a pointer-to-member c. I'm using MSVC2012 and if I don't declare the struct abc as a type definition (typedef), I can't use it.. how come?

struct abc
{
    int a;
    int b;
    char c;
};

char (struct abc)::*ptt1 = &(struct abc)::c; // Error: error C2144: syntax error : 'abc' should be preceded by ')'

typedef struct abc;
char abc::*ptt1 = &abc::c; // Compiles just fine
Paul
  • 725
  • 1
  • 6
  • 15
  • 1
    As explained in http://stackoverflow.com/questions/2750270/c-c-struct-vs-class, `struct` is just like `class` keyword (except the default member visibility), and you wouldn't write `&(class abc)::c`, would you? :) – FredericS Mar 21 '13 at 15:26

1 Answers1

7

if I don't declare the struct abc as a type definition (typedef), I can't use it.. how come?

You can, and you don't need the struct keyword, nor the typedef. Just do this:

char abc::*ptt1 = &abc::c;
Andy Prowl
  • 124,023
  • 23
  • 387
  • 451
  • But to declare a variable of that structure I need to write "struct abc myvariable;", is it correct? – Paul Mar 21 '13 at 15:27
  • @Paul: No, you don't need to. `abc myvariable;` is enough. – Andy Prowl Mar 21 '13 at 15:36
  • Today I discovered that I don't need typedef to declare a struct variable... so what's the use of typedef struct abc {..}; ? – Paul Mar 21 '13 at 15:38
  • 1
    @Paul: `typedef` is used to define a type alias. If you have a structure defined as `struct abc { ... };` and you want to give it an alternative name, you can do `typedef abc other_name;`. Then, you can use `other_name` instead of `abc`, like: `other_name a;`. That's equivalent to `abc name;`. Normally, `typedef` comes handy to shorten otherwise verbose typenames, e.g. `typedef std::map, std::string> my_map; my_map m;`. Your usage of `typedef` seems to be a heritage of C, which I do not know quite well. In C++, defining a struct does not require `typedef`. – Andy Prowl Mar 21 '13 at 15:40
  • Thank you Andy, in fact I was taught to use typedef in the C fashion but now you helped me greatly. Thank you! – Paul Mar 21 '13 at 15:58