0

I ran the below program and it is running fine. but I don't understand even if the objectaa is not initialized anywhere in the code and it is just an object pointer, then how the dummyfn of class Aa is getting called?

#include<bits/stdc++.h>
using namespace std;

class Aa
{
    public:
    int a;
    void dummyfn (string ss);
};

void Aa::dummyfn(string ss)
{
    cout<<"calling fun from Aa "<<ss<<endl;
}

class bb
{
    public:
    int b;
    Aa *objectaa;
    void bbfun();
};

void bb::bbfun()
{
    cout<<"calling the bb function"<<endl;
    string str = "ffff";
    objectaa->dummyfn(str);
}

int main()
{
    bb *objectb = new bb();
    objectb->bbfun();
    
    return 0;
}

sai akash
  • 1
  • 1
  • 2
    `dummyfn()` doesn't use any member of the `Aa()` class. So the `this` pointer in `dummyfn()` is not used and that is why you are not seeing any problem. Regardless this is undefined behavior – kuro Jun 28 '22 at 07:13
  • *"even if the objectaa is not initialized anywhere in the code"* - it is zero-filled per that trailing `()` on your ctor invoke from your `new` call. So is `b` by the way. Outside of that, it is null, and you are dereferencing it for the member call, so you're invoking undefined behavior regardless. – WhozCraig Jun 28 '22 at 07:13
  • 3
    Your code has undefined behaviour. It happens to work because `dummyfn` doesn't access any members of `Aa` – Alan Birtles Jun 28 '22 at 07:16

0 Answers0