C++ Basic Class Sample for Beginner

C++ and C have lots of differences and one of the main difference of the existence of classes. The keyword class is used to denote a class in C+. Every class in C++ have a constructor and a destructor. This sample code provides the code for a simple C++ class and associated constructor, destructor a function. All the functions defined in this basic c++ class are public.

Sample Code for Basic CPlus Plus Class

Sample Code for Basic CPlus Plus Class

The above screenshot displays how you can design a basic C++ class and add constructor, destructor and a function to it. This class uses std::cout object to display text to the console output as used in other posts of this website like Substract Numbers with C++, Hello World in C++ and others. Note that in the main function, an object of the basic class has been created and the function is called. Now have a look at the output of this C++ program given below to learn how C++ Objects work.

Output of Basic C Plus Plus Class Program

Output of Basic C Plus Plus Class Program

Whenever an object of a class in C++ is created , the constructor of the class is called automatically. In case you do not define constructor of C++ class, a default constructor is provided internally. Note after the constructor, the function is called by the main function and finally whenever a C++ object goes out of scope, the destructor is called as displayed in the screenshot above.

class CBasicClass{public:CBasicClass(){std::cout &lt;&lt; "Constructor of CBasicClassn";}~CBasicClass(){std::cout << "Destructor of CBasicClassn";}void Sayhello(){std::cout << "Hello From CBasicClassn";}};int _tmain(int argc, _TCHAR* argv[]){CBasicClassoObjectOfBasicClass;oObjectOfBasicClass.Sayhello();return 0;}

You can copy and paste above sample source code in your program to learn how to use C++ effectively. This small sample C++ project can be really helpful to quickly understand how C++ classes and objects work. Yes there is lots more to learn and stay tuned for more C++ sample projects.