Whatamia Whatamia - 1 month ago 10
C++ Question

Using functions of an Object file using C++ in a BST

I am making a Binary Search Tree and I have the following function in a .cpp file:

void MovieTree::printMovieInventory(MovieNode* node)
{
if(node)
{
while(node->rightChild && node->leftChild)
{
std::cout<<"Movie:"<<node->title<<" "<<node->quantity<<std::endl;
if(node->rightChild)
{
printMovieInventory(node->rightChild);
}
if(node->leftChild)
{
printMovieInventory(node->leftChild);
}
}
}
else
{
std::cout<<"No movies in list!"<<std::endl;
}


I am a little unsure as to how I should be referring to this function in my main.cpp file or "driver file". I referred to it in main using this:

case 3: //message is read in from file
{
MovieTree::printMovieInventory(node);
}

break;


However, Upon referencing this it just throws an error:

Driver.cpp:37:40: error: cannot call member function 'void MovieTree::printMovieInventory(MovieNode*) without object
MovieTree::printMovieInventory(node);


Not sure what this means.

full main here:

int main(int argc, char **argv)
{
bool quit = false;
string s_input;
int input;

// loop until the user quits
while (!quit)
{
MovieNode* node = new MovieNode;
printOptions();

// read in input, assuming a number comes in
getline(cin, s_input);
input = stoi(s_input);

switch (input)
{
// print all nodes
case 1: //rebuild network

break;


break;

case 3: //message is read in from file
{
MovieTree::printMovieInventory(node);
}
break;

case 4: // quit
quit = true;
cout << "Goodbye!"<< endl;
break;

default: // invalid input
cout << "Invalid Input" << endl;
break;
}
}

}

Answer

You need an instance of MovieTree. Somehwere in your code and above the switch statement, you should add:

MovieTree movieTree;

and then your switch statement will look like this:

case 3: //message is read in from file
                movieTree.printMovieInventory(node);
                break;

Alternatively, if MovieTree has no state (ie. no fields or other functions it depends on) you can mark printMoviewTree as static instead of the code above.