Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 968
Vivek Vishal Avatar asked Jan 26 '26 06:01

Vivek Vishal


1 Answers

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();
}
like image 158
juanchopanza Avatar answered Jan 29 '26 12:01

juanchopanza



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!