Home > Software design >  Difference between pointer call and refrence call
Difference between pointer call and refrence call

Time:12-24

I was randomly playing with pointers and refrences.

class Product {
    int price,qty;
    
    public:
    void setData(int price, int qty) {
        this->price = price;
        (*this).qty = qty;
    }
    void billing() {
        cout << price * qty;
    }
};

int main() {
    Product *PenObj;
    (*PenObj).setData(50,25);
    (*PenObj).billing();

    return 0;
}

I don't understand why this does not print out the bill. But when I use a refrence object it prints out the bill.

CodePudding user response:

you only declare a pointer to PenObj, but havn't create the object of PenObj. It should be Product *PenObj = new PenObj

CodePudding user response:

Product *PenObj; simply declares a pointer, but it doesn't point anywhere meaningful. You are calling setData() and billing() on an invalid Product object, which is undefined behavior.

You need to create the object, eg:

int main() {
    Product *PenObj = new Product;
    (*PenObj).setData(50,25); // or: PenObj->setData(50,25);
    (*PenObj).billing(); // or: PenObj->billing();
    delete PenObj;
    return 0;
}

Or:

int main() {
    Product PenObj;
    Product *PenObjPtr = &PenObj;
    (*PenObjPtr).setData(50,25); // or: PenObjPtr->setData(50,25);
    (*PenObjPtr).billing(); // or: PenObjPtr->billing();
    return 0;
}

In which case, you may as well just drop the pointer altogether:

int main() {
    Product PenObj;
    PenObj.setData(50,25);
    PenObj.billing();
    return 0;
}
  •  Tags:  
  • c
  • Related