简体   繁体   中英

How a pointer to an object which is not initialized by an address of object assign value to data member of class?

An pointer to object when declared uninitialized it points to some garbage location.If any data member is initialized using the same pointer then where does the data member exist without an object.Because an object can have data members, not an uninitialized pointer to an object.

I tried printing value of uninitialized "pointer to an object" before/after initializing it's data member. The value remains same it means their still no object created and pointer is pointing to any garbage value.

#include <iostream>
using namespace std;

class play {
    public:
    int runs;
};

int main() {
    play *batsman;          // Not initialized
    cout<<batsman<<endl;     // "0" means pointing to any garbage location
    batsman ->runs = 10;     // Which object's data member "runs" is been initialized?
    cout<<batsman<<endl;    //  "0" still points to some garbage location
    play obj;
    batsman = &obj;         // Initializing the pointer
    cout<<batsman<<endl;    // 0x7ffe76256e60
    return 0;
}

I expected if a pointer to an object is not initialized with any address of a object then how come it initialize or allocate value to data memeber of a class.It should be runtime error trying to allocate value to data member which does not belongs to any object.

It should be a runtime error . That is wrong, when you break the rules of C++ it is normally undefined behaviour . Undefined behaviour means anything can happen, it does not mean there must be an error, it does not mean that it won't 'work'.

Undefined behaviour is one of the things makes programming C++ hard because when your programs have bugs their behaviour is unpredictable. The advantage of undefined behaviour is that it means the compiler can generate very fast code because it doesn't have to check for things like garbage pointers, it just assumes all pointers are valid.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM