Call Function of C++ Class with NULL Pointer

Pointers in C++ are really interesting stuff and are often taken as the difficult thing to learn in C++. Pointers provide the developer functionality of dynamic memory allocation and hence are useful. This post provides a quick and dirty method of learning more about pointers in C++. The sample code presented in this post displays how you can call a member function of a c++ class without actually creating an object and without using static member function.

Call Function of a C++Class with Null Pointer

Call Function of a C++Class with Null Pointer

The above sample code has created a simple C++ class with public constructor and a non static member function. Yes in the above C++ sample code, static function is not used as was used when describing a C++ class with Static Function. Also have a look at the output of this C++ sample project to verify that the object of the class has not been created in order to call the non static member function. In case you would like to run this sample code on your own machine, copy paste from the given below code sample and try it for yourself.

#include "stdafx.h"#include <iostream> // For std::cout objectclass CPlusPlusFunctionCallUsingPointer{public:CPlusPlusFunctionCallUsingPointer(){std::cout << "Constructor of the C++ Classn";}void CplusPlusFunction(){std::cout << "Function of a C++ Classn";}};int _tmain(int argc, _TCHAR* argv[]){CPlusPlusFunctionCallUsingPointer* pOinter=NULL;pOinter->CplusPlusFunction();return 0;}

In case the non static member function accesses any member variable of the class, this function call would not work and would require you to create an object of the C++ class. This sample C++ Code of calling a non static member function also requires you to initialize the pointer to null as displayed in the above screenshot and code snipplet.

Program Output of Calling Function of a C++Class with Null Pointer

Program Output of Calling Function of a C++Class with Null Pointer

As the above screenshot displays, the project runs without any compilation or linking errors and a non static member function is called without creating an object of the C++ class. Understanding of this C++ Project requires you to have knowledge of C++ Pointers, Static Member Functions and a thorough understanding of how memory allocation is done by the operating system depending on the syntax of C++ Language and other related stuff.