Vivek Vishal
Vivek Vishal

Reputation: 21

Why Function is getting accessed without object in C++?

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?

Upvotes: 2

Views: 62

Answers (3)

john
john

Reputation: 87957

Because you have no object your code has Undefined Behaviour. Undefined behaviour means exactly what it says, it doesn't mean your program will crash, it means anything can happen, including accessing an object that doesn't exist.

One of the things that makes programming C++ hard is that you cannot rely on bugged programs to crash, sometimes they seem to work.

Upvotes: 3

juanchopanza
juanchopanza

Reputation: 227418

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();
}

Upvotes: 5

Raxvan
Raxvan

Reputation: 6505

This is undefined behavior, but it is not crashing because you are not accessing any member variables from that class so even if the pointer sc1/sc2 is random value nothing is happening.

Upvotes: 2

Related Questions