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
1

1 Answer 1

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;
Sign up to request clarification or add additional context in comments.

5 Comments

But to declare a variable of that structure I need to write "struct abc myvariable;", is it correct?
@Paul: No, you don't need to. abc myvariable; is enough.
Today I discovered that I don't need typedef to declare a struct variable... so what's the use of typedef struct abc {..}; ?
@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::vector<int>, 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.
Thank you Andy, in fact I was taught to use typedef in the C fashion but now you helped me greatly. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.