In the following program.
#include<iostream>
using namespace std;
class Base{
public:
Base(){
cout<<"I am Constructor"<<endl;
}
void method();
};
void Base::method(){
cout<<"I am method"<<endl;
}
int main()
{
Base *sc1;
Base *sc2;
sc1->method();
sc2->method();
}
the output I am getting is as follows
I am method I am method
How can this happen as no object is created?
It is undefined behaviour, so "anything" can happen. It probably runs because you do not access anything (implicitly or explicitly) via the this pointer.
This would be more likely to fail:
struct Foo
{
int foo() const { return i; }
int i;
};
int main()
{
Foo* f;
f->foo();
}
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