sivan
sivan

Reputation: 120

What will a pointer to a object point to outside the object scope in C++

class Foo{
    private: 
       int i;
    public:
       Foo(int a)
       {
          i = a;
       }

        int getI() {return i;}
};

int main()
{
    Foo* f;
    if(true)
    {
        Foo g(1);
        f = &g;
    }

    cout << f->getI() << endl;
    return 0;
 }

In the code above, the g object of Foo class will go out of scope once it exit the if clause. So when the cout statement is executed, will it be printing 1?

Upvotes: 0

Views: 175

Answers (5)

Sam Cristall
Sam Cristall

Reputation: 4387

It will cause undefined behavior. Legally it can do anything: it could print 1, it could print 42, it could order a pizza or it could end all life in the universe. All are legal results. Undefined behavior is very bad.

Once g goes out of scope, it is no longer defined, f now points to an undefined object and dereferencing f, while not forbidden, is not supported in any defined way.

Upvotes: 3

JBL
JBL

Reputation: 12907

It may. Or it may not. The object will be destroyed, the pointer will point to the same adress in memory.

But dereferencing this pointer is undefined behavior, and that's not what you want. Indeed, what's the use of a program which nobody can say what'll it do ?

Upvotes: 0

Jaffa
Jaffa

Reputation: 12710

The object will be destroyed, calling the object's destructor.

The pointer will still point to the same memory location.

Accessing it is an undefined behavior, so it could do anything at all.


You cannot assume the behavior of this, but if your code contains only this code then there might be a good chance that it will effectively print 1 as the memory will not have been overwriten.

But do not assume this will be the case !

Upvotes: 1

Pierre Fourgeaud
Pierre Fourgeaud

Reputation: 14510

You get an Undefined behavior. You cannot know what cout will print...

Maybe sometimes it will print the correct value but you can be sure that the day of the demo it will not be correct...

Upvotes: 0

usr
usr

Reputation: 171178

The behavior is undefined. It could do anything at all. You must absolutely avoid undefined behavior.

Upvotes: 4

Related Questions