Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Difference between pointer call and refrence call

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading