15

This might be a stupid question but I can't find a lot of information on the web about creating your own default constructors in C++. It seems to just be a constructor with no parameters. However, I tried to create my default constructor like this:

Tree::Tree()  {root = NULL;}

I also tried just:

Tree::Tree() {}

When I try either of these I am getting the error:

No instance of overloaded function "Tree::Tree" matches the specified type.

I can't seem to figure out what this means.

I am creating this constructor in my .cpp file. Should I be doing something in my header (.h) file as well?

4 Answers 4

17

Member functions (and that includes constructors and destructors) have to be declared in the class definition:

class Tree {
public:
    Tree(); // default constructor
private:
    Node *root;

};

Then you can define it in your .cpp file:

Tree::Tree() : root(nullptr) {
}

I threw in the nullptr for C++11. If you don't have C++11, use root(0).

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! I read class definition before but didn't know what that meant so I probably ignored it. Now it makes more sense.
Every class has to have a definition. The definition lists the member functions and member data for the class. Wherever you use the class, your code has to see the class definition. So the class definition almost always goes into a header file that you can #include in any source file that uses the class. In the source file or files where you define the member functions you also #include the header file, then write the function definitions.
9

C++11 allows you to define your own default constructor like this:

class A {  
    public:
        A(int);        // Own constructor
        A() = default; // C++11 default constructor creation
};

A::A(int){}

int main(){
    A a1(1); // Okay since you implemented a specific constructor
    A a2();  // Also okay as a default constructor has been created
}

Comments

5

It isn't sufficient to create a definition for any member function. You also need to declare the member function. This also applies to constructors:

class Tree {
public:
    Tree(); // declaration
    ...
};

Tree::Tree() // definition
    : root(0) {
}

As a side note, you should use the member initializer list and you should not use NULL. In C++ 2011 you want to use nullptr for the latter, in C++ 2003 use 0.

1 Comment

Thanks! That's kind of what I was thinking but wasn't sure how to declare it.
4

Yes, you need to declare it in your header. For example place the following inside the declaration of the tree class.

class Tree {
    // other stuff...
    Tree();
    // other stuff...
};

1 Comment

Thanks! I knew it was something like that. I think I need to learn a little more about header files.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.