Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a default constructor in C++

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?

like image 827
user1824239 Avatar asked Nov 14 '12 19:11

user1824239


People also ask

Can we create constructor in C?

A Constructor in C is used in the memory management of C++programming. It allows built-in data types like int, float and user-defined data types such as class. Constructor in Object-oriented programming initializes the variable of a user-defined data type.

What is default constructor with example?

A default constructor is a constructor that either has no parameters, or if it has parameters, all the parameters have default values. If no user-defined constructor exists for a class A and one is needed, the compiler implicitly declares a default parameterless constructor A::A() .

Does compiler create default constructor?

In C++, the compiler creates a default constructor if we don't define our own constructor. In C++, compiler created default constructor has an empty body, i.e., it doesn't assign default values to data members. However, in Java default constructors assign default values.


2 Answers

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
}
like image 199
Kevin Katzke Avatar answered Oct 08 '22 11:10

Kevin Katzke


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).

like image 41
Pete Becker Avatar answered Oct 08 '22 11:10

Pete Becker