'Parts of a structure in C++ [closed]

Here is a code of a structure. On that there is a BSTree function included on the structure. I am stuck because I do not understand how a function can get called when is inside the structure. Here is the structure and if anyone can explain the trick would be helpful:

struct BSTree{

    int data;
    BSTree *left;
    BSTree *right;

    BSTree(int value){ 
        data = value;
        left = 0;
        right = 0;
    }
};


Solution 1:[1]

There is no trick. In C++ structs and classes can have data and function members.

The particular function you have there is a constructor, it's used to create an instance of the struct, an object of this type. A particular struct or class can have many constructors with different parameters, or no parameters at all.

struct BSTree{

    int data;    
    BSTree *left;
    BSTree *right;
           
    BSTree(int value){ 
    data = value;
    left = 0;
    right = 0;
    }
};

This can then be used:

int main(){
  
   BSTree bst(3); //this will create a BSTree object where the data members are initialized
}                 //as stated in the constructor definition

This is just scratching the surface. You will need a good book to learn more about this. Here is a good list you can pick from.

Solution 2:[2]

That's the definition of the class's constructor.

It's a function called automatically when a BSTree instance is created.

You can read more in your C++ book.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Asteroids With Wings