Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ function called without object initialization

Why does the following code run?

#include <iostream>
class A {
    int num;
    public:
        void foo(){ num=5; std::cout<< "num="; std::cout<<num;}
};

int main() {
    A* a;
    a->foo();
    return 0;
}

The output is

num=5

I compile this using gcc and I get only the following compiler warning at line 10:

(warning: 'a' is used uninitialized in this function)

But as per my understanding, shouldn't this code not run at all? And how come it's assigning the value 5 to num when num doesn't exist because no object of type A has been created yet?

like image 611
Apoorva Iyer Avatar asked Mar 19 '11 06:03

Apoorva Iyer


1 Answers

The code produces undefined behavior, because it attempts to dereference an uninitialized pointer. Undefined behavior is unpredictable and follows no logic whatsoever. For this reason, any questions about why your code does something or doesn't do something make no sense.

You are asking why it runs? It doesn't run. It produces undefined behavior.

You are asking how it is assigning 5 to a non-existing member? It doesn't assign anything to anything. It produces undefined behavior.

You are saying the output is 5? Wrong. The output is not 5. There's no meaningful output. The code produces undefined behavior. Just because it somehow happened to print 5 in your experiment means absolutely nothing and has no meaningful explanation.

like image 199
AnT Avatar answered Oct 12 '22 23:10

AnT