Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I accidentally called a member function without own class object. But how does this work?

Here is my code.

class IService {
};

class X_Service {
public:
    void service1() {
        std::cout<< "Service1 Running..."<<std::endl;
    }
};


int main() {
    IService service;
    auto func = reinterpret_cast<void (IService::*)()>(&X_Service::service1);
    (service.*(func))();
    return 0;
}

I don't understand how this works. I didn't inherit IService and didn't create a X_Service object but it works. Can someone explain this?

like image 347
s3ms Avatar asked Feb 22 '20 22:02

s3ms


1 Answers

Your confusion probably comes from the misunderstanding that because something compiles and runs without crashing, it "works". Which is not really true.

There are many ways you can break the rules of the language and still write code that compiles and runs. By using reinterpret_cast here and making an invalid cast you have broken the rules of the language, and your program has Undefined Behaviour.

That means it can seem to work, it can crash or it can just do something completely different from what you intended.

In your case it seems to work, but it's still UB and the code is not valid.

like image 102
super Avatar answered Sep 20 '22 09:09

super