I understand that pointer has reference to object? In order not to duplicate it
class A
{
A(){};
}
A *ptrA;
- why do we need a pointer to own class?
- how does it work?
CodePudding user response:
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;
}