0

I cannot figure out how this compiles. It seems like it should not, and if I use a value other than NULL in the constructor it will not.

#include <stdio.h>


class MyClass{
    private:
        int *first;
    public:
        MyClass();
};

MyClass::MyClass(){

    int whatever = 42;
    //int* MyClass::*first = &whatever;//This does not compile
    int* MyClass::*first = NULL;//This compiles
}

int main(){

    MyClass doSomething;
    return 1;
}

It seems that generally the type Class::member = value syntax is used for static vars, which this is not.

Also, there is an asterisk before the member name, which confuses things even more.

If I switch the lines to the one that is commented out, the compiler complains, as expected.

error: cannot convert ‘int*’ to ‘int* MyClass::*’ in initialization

While I did expect an error, I have no idea what the type int* MyClass::* is. Or how it could be used.

mtfurlan
  • 1,024
  • 2
  • 14
  • 25
  • 3
    I am not sure but I suspect you have created a pointer to member variable. http://stackoverflow.com/questions/670734/c-pointer-to-class-data-member – Neil Kirk Nov 16 '15 at 04:50
  • try `int *MyClass::*first = &MyClass::first;`. Giving it a different name might be a bit less confusing. – M.M Nov 16 '15 at 04:59
  • Where is the _static vars_ ? – P0W Nov 16 '15 at 05:04
  • @NeilKirk Yeah, I think you're right. I got this from a friend trying to grade a students code, and it was just weird that it compiled at all. – mtfurlan Nov 16 '15 at 05:07

1 Answers1

0

This is a pointer to data member. You cannot initialize it with an ordinary pointer, that is why the commented out expression does not compile.

Eugene
  • 6,194
  • 1
  • 20
  • 31