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?
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.
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() .
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.
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
}
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)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With