In continuation of my previous blog on C++ , we will be understanding the concept of classes in an easy fashion as usual ☺️ .
2. What is a class?
A class is a blueprint of any entity, literally. For a building, a blueprint describes the shape, number of rooms, entries etc. A class describes the basic structure of anything that can be described and designed by software.
3. Real world example of class
I was teaching my little boy about seasons, so let’s take that as an example to understand what we really mean by a class.
A season can be described by the weather condition, clothes that people wear, diseases prevalent in that season, plants flourishing etc.
seasons(); //default constructor
seasons(int plants); //constructor with 1 parameter
int getWeather(); //class function
};// Class seasons definition ends here
For summer season, weather will be sunny, clothes will be cotton , and so on. And for winters, cold weather and woollen clothes . Easy, right ☺️ . This will get clearer when we will discuss inheritance later.
4. Objects and class member access
We are aware that there are variables of type int, char, float etc. Similarly, we can define variables of the type of class we create. These class variables are called objects.
For our above example of class seasons, we can create object as:
We can access class members as:
5. Constructors and destructors
When an object is created, a default function of the class is called. This default function is called constructor. It doesn’t have a return type. They are mostly used to initialize class parameters. However, there can be multiple constructors with different number of parameters.
The above line will call the default constructor, seasons() with zero parameters.
The above line will call the constructor seasons(int plants) .
A destructor is the opposite of constructor ☺️ . It is called just before a class object dies. They are prefixed by ~ (tilda) . They don’t have a return value, and they cannot take any parameters. They can be used to release any allocated memory once it is not needed .
~seasons () is the destructor in the above example.
Friends, I hope you feel comfortable with classes now . As a side effect, you may start looking at everything around you in terms of classes now. Creepy 😁 .
In our next tutorial, we will be taking up inheritance. Happy learning ☺️ .