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 !
Your program has undefined behaviour because you are accessing bashful
before it has been constructed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With