Create C++ Object with Pointer

Objects in C++ can be created with pointers and this post provides quick and short C++ tutorial displaying how to create object in c++ with pointer. The C++ sample code provided in this post displays a small C++ class without any functions apart from constructor and destructor. Constructor and Destructor are functions which gets called automatically as and when object of C++ is created and deleted respectively.

C++ Class Object With Pointer

C++ Class Object With Pointer

As displayed above the class contains only public constructor and destructor. The Constructor and Destructor of the C++ class simply display appropriate messages to the console output. Now have a look at the main function of the program in which a pointer has been created and a new object of the class is created with the new keyword and finally the object is destroyed with the delete keyword. This is the simplest way in which you can create and delete C++ class objects using pointers. Now have a look at the output of the C++ program given below.

Output of C++ Class Object With Pointer Program

Output of C++ Class Object With Pointer Program

As displayed in the screenshot above, the constructor gets called in which the std::cout object has been coded to display text and finally the destructor of the object gets called. Also remember that the public keyword lets us create object of the C++ class outside the class. You can copy the source code from the given below code snipplet or write your own with different class name and build the C++ project yourself. In case you would like some help in understanding how to create and build your C++ project, do have a look at the Hello World C++ Project which displays all the steps required to build and run the C++ project using Microsoft Visual Studio.

#include "stdafx.h"#include <iostream>class CLearnObjectsWithPointers{public:CLearnObjectsWithPointers(){std::cout << "Constructor of C++ Classn";}~CLearnObjectsWithPointers(){std::cout << "Destructor of C++ Classn";}};int _tmain(int argc, _TCHAR* argv[]){CLearnObjectsWithPointers* pointerToObject;pointerToObject = new CLearnObjectsWithPointers();delete pointerToObject;return 0;}