Object creation question

I thought I understood how pointers and objects work, but I am confused when this happened to me. I was not able to create an object using the new operator. I had to create a pointer to the class and assign the new object to the pointer. Attaching the code below

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
struct tree{
	tree *left, *right;
	int value;
};

class BST{
   tree *root;
public: 
   BST(){
	   root = NULL;
   }
   BST(int _value){
	   root = new tree();
	   root->left = root->right = NULL;
	   root->value = _value;
   }
};
tree* LinkedListToBST(Node *root){
   BST llTree = new BST;
}


In the code attached, I cannot do BST llTree = new BST;.
I see an error
No suitable constructor exists to convert from BST* to BST

The error goes away when I change it to BST *llTree = new BST;
Can someone tell me what is happening in this is the case?
Last edited on
It is as error states. new returns a pointer to the object in dynamic memory.
On line 19 you declare llTree to be object, not a pointer to object. So you cannot assign a pointer to object.
Pointers are more easily understood with examples!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
BST obj; // this creates a BST object named 'obj'

BST* ptr;  // this creates a pointer named 'ptr', but not a BST object
   // Once initialized, the pointer merely contains an address to an existing object

ptr = &obj;  // now, 'ptr' points to our 'obj' object

// 'new' works differently.  Rather than creating a named object, it creates an UNNAMED
//  object, and gives you a pointer to it.

BST* p2 = new BST;  // 'new BST' creates an unnamed BST object.  For this example, let's call
   // this object 'foo'.  The new keyword will also return a pointer to the created object, so
   // after this line, p2 will point to 'foo'

// so now we have 2 objects:  obj and foo
// and we have 2 pointers:  ptr (points to obj), and p2 (points to foo)


// The 'delete' keyword is slightly deceptive.  You must only delete what you created
//  with new:
delete p2;  // <- this does not actually delete p2.  It will delete whatever p2 points to.
   //  so in fact, this will delete 'foo'.  p2 remains a pointer just as it was before, the
   //  only difference is the object it pointed to no longer exists. 
Wow, thanks @MiiNiPaa and @Disch. @Disch - thanks for the list, it will serve as a reference for the future.
Topic archived. No new replies allowed.