Create a default constructor in C ++

This may be a stupid question, but I cannot find much information on the Internet about creating my own default constructors in C ++. It seems to be just a constructor without parameters. However, I tried to create my default constructor as follows:

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

I also tried just:

 Tree::Tree() {} 

When I try to do this, I get an error:

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

I can’t understand what this means.

I create this constructor in a .cpp file. Should I do something in my header file ( .h )?

+4
source share
4 answers

Member functions (and which include constructors and destructors) must be declared in the class definition:

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

Then you can define it in the .cpp file:

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

I chose nullptr for C ++ 11. If you do not have C ++ 11, use root(0) .

+12
source

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

 class Tree { // other stuff... Tree(); // other stuff... }; 
+4
source

It is not enough to create a definition for any member function. You also need to declare a member function. This also applies to constructors:

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

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

+4
source

C ++ 11 allows you to define your own default constructor as follows:

 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 } 
+3
source

Source: https://habr.com/ru/post/1446075/


All Articles