The concept of constructors in C programming

in hive-175254 •  2 years ago 

Today we will make use of constructors and create a normal c program to know how they work. They are very useful and important feature of any programming language.

Here is the code itself.

Screenshot 2023-01-05 221021.png

You can copy the entire code below :

#include <stdio.h>
#include <stdlib.h>

typedef struct
{
int x;
int y;
} Point;

Point* createPoint(int x, int y)
{
Point* p = (Point*) malloc(sizeof(Point));
p->x = x;
p->y = y;
return p;
}

int main()
{
Point* p1 = createPoint(10, 20);
printf("Point: (%d, %d)\n", p1->x, p1->y);
free(p1);
return 0;
}

In this example, the createPoint function acts as a constructor for the Point struct. It takes two integer arguments, x and y, and returns a pointer to a dynamically allocated Point object with those values. The object is created using the malloc function, which allocates memory on the heap.

In the main function, we create a Point object by calling the createPoint function and storing the result in a Point* variable. We can then access the fields of the object using the arrow operator (->).

It is important to remember to free the memory allocated by malloc when it is no longer needed, as we do in the main function with the free function.

Output of the above program will be :

Screenshot 2023-01-05 221034.png

This output is produced by the following line of code:

Screenshot 2023-01-05 221048.png

It prints the values of the x and y fields of the Point object pointed to by p1. In this case, the values are 10 and 20, respectively, so the output is Point: (10, 20).

If you also want to learn coding then find your teacher according to your language. For me i am comfortable with hindi language and follow hindi teachers.

You can refer to my teacher below in case you are also comfortable with hindi.

Source

I will soon call myself a trader and a small programmer together.

Happy trading and keep learning what you love.

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!
Sort Order:  

Great information. Constructors are an important part of object-oriented programming in C++ and are used to create and initialize objects of a class when they are created.