How To Create A Pointer To An Object In C++
C++ Pointers to Objects
PreviousNext
You can access an object either directly, or by using a pointer to the object.
To access an element of an object when using the actual object itself, use the dot operator.
To access a specific element of an object when using a pointer to the object, you must use the arrow operator.
To declare an object pointer, you use the same declaration syntax that you would use for any other pointer type.
Example
The next program creates a simple class called My_Class, defines an object of that class, called ob, and defines a pointer to an object of type My_Class, called p.
It then illustrates how to access ob directly, and how to use a pointer to access it indirectly.
// A simple example using an object pointer. # include <iostream> using namespace std; class My_Class { int num; public: void set_num(int val) {num = val;} void show_num(); }; void My_Class::show_num() { cout << num << "\n"; } int main() { My_Class ob, *p; // declare an object and pointer to it ob.set_num(1); // access ob directly ob.show_num(); p = &ob; // assign p the address of ob p->show_num(); // access ob using pointer return 0; }
Notice that the address of ob is obtained by using the & (address of) operator in the same way that the address is obtained for any type of variable.
When a pointer is incremented or decremented, it is increased or decreased in such a way that it will always point to the next element of its base type.
The same thing occurs when a pointer to an object is incremented or decremented: the next object is pointed to.
To illustrate this, the preceding program has been modified here so that ob is a two-element array of type My_Class.
Notice how p is incremented and decremented to access the two elements in the array.
// Incrementing and decrementing an object pointer. # include <iostream> using namespace std; class My_Class { int num; public: void set_num(int val) {num = val;} void show_num(); }; void My_Class::show_num() { cout << num << "\n"; } int main() { My_Class ob[2], *p; ob[0].set_num(10); // access objects directly ob[1].set_num(20); p = &ob[0]; // obtain pointer to first element p->show_num(); // show value of ob[0] using pointer p++; // advance to next object p->show_num(); // show value of ob[1] using pointer p--; // retreat to previous object p->show_num(); // again show value of ob[0] return 0; }
The output from this program is.
PreviousNext
Related
- C++ Class Access Specifiers
- C++ Structure as class
- C++ Class this Keyword
- C++ Arrays of Objects
- C++ Initializing Object Arrays
How To Create A Pointer To An Object In C++
Source: https://www.demo2s.com/cpp/cpp-pointers-to-objects.html
Posted by: compoorwastincer.blogspot.com
0 Response to "How To Create A Pointer To An Object In C++"
Post a Comment