YouTip LogoYouTip

Cpp Pointer To Class

# C++ Pointers to Classes [![Image 3: C++ Classes & Objects](#) C++ Classes & Objects](#) A pointer to a C++ class is similar to a pointer to a structure. To access members of a pointer to a class, you use the member access operator **->**, just like with a pointer to a structure. Like all pointers, you must initialize the pointer before using it. In C++, a pointer to a class points to an object of that class. Similar to ordinary pointers, a pointer to a class can be used to access the object's member variables and member functions. **Declaring and Initializing a Pointer to a Class** ## Example #include class MyClass { public: int data; void display(){ std::cout<<"Data: "<< data << std::endl; } }; int main(){ // Create a class object MyClass obj; obj.data=42; // Declare and initialize a pointer to the class MyClass *ptr =&obj; // Access member variable via pointer std::cout<<"Data via pointer: "<data <display(); return 0; } When the above code is compiled and executed, it produces the following result: Data via pointer: 42Data: 42 **Dynamic Memory Allocation** A pointer to a class can also be used to dynamically allocate memory and create an object of the class: ## Example #include class MyClass { public: int data; void display(){ std::cout<<"Data: "<< data <data =42; // Call member function via pointer ptr-
← Lua Basic SyntaxLua Tutorial β†’