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

what does it mean pointer to own Class&

I understand that pointer has reference to object? in order no to duplicate it

class A 
{
    A(){};
}
A *ptrA;
1) why do we need a pointer to own class,
2) how does it work

>Solution :

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

The type of ptrA is A * which mean class A pointer, so, ptrA is pointer of type class A.
It can hold the reference of memory of object of type A.

Example:

#include <iostream>

class A {
public:
    A() {
        std::cout << "Constructor" << std::endl;
    }
    void test() {
        std::cout << "test() member function" << std::endl;
    }
    ~A() {
        std::cout << "Destructor" << std::endl;
    }
};

int main() {
    A* ptrA = new A(); // Dynamic allocation of object of type A
    ptrA->test();
    delete ptrA;       // Delete the object created dynamically

    A objA;            // object of type A created locally

    ptrA = &objA;      // ptrA assigned address of object objA
    ptrA->test();

    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