Are member functions guaranteed before creating any object?

Consider the following example:

#include <iostream>

class myclass
{
public:
    void print() { std::cout << "myclass"; }
};

int main()
{
    myclass* p = 0x0; // any address

    p->print(); // prints "myclass"
}

      

I have not called the member function print

through an object of type myclass. Instead, I called it a pointer to a random location in memory. Is this specific behavior? That is, is the member function guaranteed to execute before any type object is created myclass

?

+2


source to share


2 answers


Calling a null pointer (0) causes a call to undefined. The program can do anything it wants, including work as expected.



In particular, you avoid it here because the member function print()

does not reference any member variables (there are none), but the compiler may still have generated code that will crash on you. And if the member function referred to any member variables, you would be serious about undefined behavior. It's probably not worth trying to figure out how much you can do this, because you are causing undefined behavior that can vary from compiler to compiler, version to version, platform to platform and run.

+11


source


You may find that changing your function print()

can help illuminate the situation:

void print() { std::cout << "myclass, this=" << this; }

      

This outputs the C ++ pointer value this

, which in your example would be 0

(or whatever you set p

to). Accessing any data member of the class will be the same as dereferencing this

, which, if it does not point to a validly constructed instance myclass

, results in undefined behavior.



You will also run into problems if you declare your function as virtual

:

virtual void print() { std::cout << "myclass"; }

      

This implementation probably won't print anything before crashing. The reason is that the compiler generates code to look vtable

at the object when the virutal function is called to find out which function to actually call. Without a valid object to fail.

+2


source







All Articles