Naz Naz - 8 months ago 59
C++ Question

Object not instantiating properly

I am currently using VS2015 for this.

I am trying to create a binary search tree in c++ so that I can learn both the language and the data structure while trying to see if I can follow good practices. However, I am coming through a problem where I am not properly instantiating the object properly in the driver file.


#pragma once

Properties of Binary Search Tree:

1.) Elements less than root will go to the left child of root
2.) Elements greater than root will go to the right child of root

#include <memory>

// Binary Search Tree handler class
class BSTHeader {

Naive implementation of BSTNode (non-generic version)

Nested class is private, but it's internal fields and member functions
are public to outer class: BSTHeader
class BSTNode {
int data;
std::unique_ptr<BSTNode> left;
std::unique_ptr<BSTNode> right;

BSTNode(int val) {
data = val;
left = NULL;
right = NULL;
~BSTNode() {}

std::unique_ptr<BSTNode> root; // Root of BST
unsigned int size; // Total amount of nodes in tree from root

BSTHeader(int val);
bool insert(std::unique_ptr<BSTNode>& root, int val);


#include "BSTHeader.h"

BSTHeader::BSTHeader() {
root = NULL;
size = 0;

BSTHeader::BSTHeader(int val) {
root = std::unique_ptr<BSTNode>(new BSTHeader::BSTNode(val)); // Smart pointer to an internal BSTNode
size = 1;

BSTHeader::~BSTHeader() {} // Empty destructor from use of smart pointer

Member functions:
bool BSTHeader::insert(std::unique_ptr<BSTNode>& root, int val) {
if (root == NULL) { // Place new element here
root = std::unique_ptr<BSTNode>(new BSTHeader::BSTNode(val));
return true;

if (val < root.get()->data) { // val < root
insert(root.get()->left, val);

else if (val > root.get()->data) { // val > root
insert(root.get()->right, val);

The issue I get is here, where I believe I am trying to instantiate a BSTHeader object.


#include "BSTHeader.h"

int main()
BSTHeader::BSTHeader bst(); // <----- ERROR
return 0;

The error I am getting is
cannot determine which instance of overloaded function "BSTHeader:BSTHeader" is intended

However, whenever I do:
BSTHeader bst()

I am not able to access the
insert(..., ...)
function for the object doing
bst.insert(..., ...)
due to
expression must have class type
even though the error above does not appear.

Yet everything works fine and I am able to access all the member methods by doing this:
BSTHeader bst(5)
by using the overloaded constructor.

I am not sure whether its a namespace issue or not. I feel as though I am missing something.


The line

BSTHeader::BSTHeader bst();   // <----- ERROR

is a declaration of a function named bst that takes no arguments and returns a BSTHeader::BSTHeader.

This is known as the "most vexing parse", and often described in less polite language.

If you want to instantiate an instance, giving the constructor no arguments, remove the ().