简体   繁体   中英

C++: No default constructor exists for parent class

I am writing the class file for a binary search tree (BST), which extends from the class (Tree). However, I receive the following error in my IDE for the current file ( bst.cpp )

在此处输入图像描述 stating:

no default constructor exists for class "Tree"

In compilation, I receive the following error:

no matching function for call to 'Tree::Tree()'

This seems strange, considering that I have already defined a default constructor in my Tree class implementation and have imported the class into my bst.cpp file:

// Import dependencies
#include "datastructure.hpp"
#include "tree.cpp"

// Import libraries
#include <fstream>
#include <sstream>

using namespace std;

BST::BST() {
    
}

void BST::solution(const char *input_path, const char *output_path)
{
}

Below is datastructure.hpp :

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

typedef struct TreeNode { 
   int key;
   int val;
   bool flag;
   int num_children;
   TreeNode **children;
} TreeNode; 

class Tree {
    protected:
        TreeNode* root;
        int max_width;
    public:
        Tree(int width);
        static void solution(const char *input_path, const char *output_path);

};

class BST: public Tree {
    protected:
        int max_width = 2;
        
    public:
        BST();
        static void solution(const char *input_path, const char *output_path);
};

And finally, below is my tree.cpp :

#include "datastructure.hpp"

#include <fstream>
#include <sstream>
#include <queue> 

using namespace std;

Tree::Tree(int width) {
    max_width = width;
}

void Tree::solution(const char *input_path, const char *output_path)
{
}

You got it there, Tree does not have a default constructor. As a result of that, you cannot default-construct a BST , because the Tree that is inside it will not know how to construct itself.

You have to member-initialize it.

BST::BST() : Tree(1) {}

Are you sure you don't want to pass that value to the constructor of BST though?

BST::BST(int w) : Tree(w) {}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM