A pointer to a class is a variable that holds the memory address of an object of that class. It allows us to access the object's properties and methods from the pointer variable. Pointers to classes are useful in situations where we need to pass objects between functions, allocate memory dynamically, or create linked data structures like linked lists, trees, and graphs.
Pointer to a class is declared with the same syntax as a pointer to any other data type. The only difference is that we need to specify the class type in the declaration.
#include <iostream>
using namespace std;
class Cls{
public:
string someStr = "Content";
void printStr() {
cout << someStr << endl;
}
};
int main() {
Cls *pTr = new Cls();
pTr->printStr();
Cls *Blah = new Cls();
Blah->printStr();
return 0;
}
This code demonstrates the use of a pointer to a class. In this example, a class named Cls
is defined with a string variable someStr
and a function printStr()
to print the string. In the main()
function, two pointers of type Cls
are created dynamically using the new
keyword.
The first pointer pTr
is assigned the address of a new Cls
object, and the printStr()
function is called on it using the arrow operator ->
.
The second pointer Blah
is also assigned the address of a new Cls
object, and the printStr()
function is called on it using the arrow operator.
This code shows how a pointer to a class can be used to create multiple objects of the class dynamically and call their member functions using the arrow operator.
No comments:
Post a Comment