1

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;
    }
};
anastaciu
  • 23,467
  • 7
  • 28
  • 53
Bixo
  • 95
  • 10
  • 2
    Show the whole snippet. Your question is unclear. – Hatted Rooster May 18 '20 at 17:30
  • This is the whole structure of which will be used for a binary search tree where I need this structure to store the data and create the tree. But I do not understand why the function should be done inside the structure instead of outside it. – Bixo May 18 '20 at 17:32
  • 14
    You need to pick up a good C++ book - this is completely basic C++ stuff (constructor and member functions). – Mat May 18 '20 at 17:34
  • 2
    The question you're trying to ask here is _"What is a constructor?"_ – Drew Dormann May 18 '20 at 17:38

2 Answers2

3

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.

anastaciu
  • 23,467
  • 7
  • 28
  • 53
  • 2
    `struct` members are public by default. – Kane May 18 '20 at 18:12
  • @anastaciu what about in C? Can structures have function members on them? – Bixo May 18 '20 at 20:47
  • 1
    @Bixo, unfortunately they can't, that would be nice though... – anastaciu May 18 '20 at 20:49
  • 1
    @anastaciu Thank you for making this clear because I was being confused with C and C++ and this gives the answer of my main problem. Because in C I know the structs create a new type of variable but when I saw it on C++ I thought they were the same as C. Thank you a lot! – Bixo May 18 '20 at 20:50
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.

Asteroids With Wings
  • 17,071
  • 2
  • 21
  • 35