Chapter 3 – Object-Oriented Programming: Part 1


A class is simply a container for methods and variables that should be grouped in any way.

The constructor and destructor for such class is automatically created by the compiler (in case we don’t define new ones), so it can create and destroy objects of such class without extra work.

The constructor is a function that has the same name as the class, whereas the destructor is similar, but it has a ~ before the name.

Object creation

When we want to create an instance of that class, we do the following:

What other ways we have to create an instance, if we also want to assign a value to the data variable?

We can see that none of these options work. But why?

Because the compiler generated a constructor that doesn’t receive any parameter.

Therefore, for that to work, we need to create our own constructor, that accepts an integer.

The third line (obj_3) is something that we may not want – it performs an implicit conversion from an integer to type MyClass.

If we want to disallow that from happening, we need to declare the constructor as explicit.

Now, we need to explicitly use the class name when we want to create an object using the assignment operator (a = b).

In case we have a reference in our class, we need to point it to an actual memory address – otherwise the code will not compile.

An example of what i mean by that and how to solve it can be seen below:


Encapsulation is the process of combining data and functions into a single unit called class. In Encapsulation, the data is not accessed directly; it is accessed through the functions present inside the class.

Here, we can talk about struct and classes.

Struct were inherited from C, and there’s not a big difference between them and classes.

The main difference is the default access level for the methods and variables.

We can see that we can simply access data from the struct, but not from the class – that is because the struct allow public access to everything, by default, whereas the classes keep everything private by default.

You may also like...