Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why could this C++ program run successfully even without constructing the class object?

Tags:

c++

Why do this C++ program could run successfully even without constructing the class object? Let's see the code as below:

#include<iostream>

using namespace std;

class Dopey
{
  public:
    Dopey() {cout << "Dopey\n";}
};

class Bashful
{
  public:
    Bashful() { cout << "BashFul\n";}
    void f() { cout << " f \n";}
    int i;
};

class Sneezy
{
  public:
    Sneezy(int i) {cout << "copy int \n";}
    Sneezy(Bashful d) { cout << "copy Bashful\n";}
    Sneezy(Bashful* d) {d->f();d->i=100;} //How could this be correct without    
                                              //  constructing d !!!!!!!!
    Sneezy();
};

class Snow_White
{
  public:
    Snow_White();
    Dopey dopey;
    Sneezy sneezy;
    Bashful bashful;
  private:
    int mumble;
};

Snow_White::Snow_White() : sneezy(&bashful)
{
    mumble = 2048;
}

int main()
{

    Snow_White s;

    return 0;
}

This program could run successfully , the cout are as below:

Dopey
f
BashFul

see, without constructing bashful,the f() could be invoked, why? and when i change the function Snow_White::Snow_White() to the below:

Snow_White::Snow_White() : sneezy(bashful)
{
    mumble = 2048;
}

it also runs successfully without constructing bashful , the cout are as below:

Dopey
copy Bashful
Bashful

Any interpretation will be appreciated ! THX !

like image 773
freeboy1015 Avatar asked Nov 14 '12 02:11

freeboy1015


1 Answers

Your program has undefined behaviour because you are accessing bashful before it has been constructed.

like image 108
Mankarse Avatar answered Oct 01 '22 22:10

Mankarse