I have a .cpp file which defines the header 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 {
public:
int data;
std::unique_ptr<BSTNode> left;
std::unique_ptr<BSTNode> right;
BSTNode(int val) {
data = val;
left = nullptr;
right = nullptr;
}
~BSTNode() {}
};
// Internal fields
std::unique_ptr<BSTNode> root; // Root of BST
unsigned int size; // Total amount of nodes in tree from root
// Internal methods
bool insert(std::unique_ptr<BSTNode>& root, int val);
bool search(std::unique_ptr<BSTNode>& root, int val);
std::unique_ptr<BSTNode>& find_min(std::unique_ptr<BSTNode>& root) {
if (root.get()->left == nullptr) {
return root;
}
else {
return find_min(root.get()->left);
}
}
public:
BSTHeader();
BSTHeader(int val);
~BSTHeader();
// API
bool insert(int val);
bool search(int val);
// Getters
int get_root_val();
}
The nested class BSTNode is private. However when I try to declare a function std::unique_ptr<BSTNode> find_min(std::unique_ptr<BSTNode>& root) in the header and define it in the .cpp file, I get an access error since I cannot return a smart pointer to a private object (makes sense, but this is a private function and i'm only defining it!). But I do not get an error if I define the function within the header file like I have above.
Is there a reason why it returns an error in the .cpp file defining the function but not when it is defined in the header file even though it is a private method? Do I have to declare and define all methods in the header file that returns a smart pointer to a BSTNode?
Aucun commentaire:
Enregistrer un commentaire