DEV Community

Discussion on: C++ Interview Questions

Collapse
 
pgradot profile image
Pierre Gradot • Edited

Hey there!

Some comments :)

There are three types of constructors

You are missing a 4th type: move constructor. It has been around for almost 10 years now!

The compiler automatically provides a default constructor even if we do not initialize one.

This is partially true. They are rules to decide if the default constructor can be implicitly defined by the compiler. It is possible that you have to explicitly define it. See en.cppreference.com/w/cpp/language..., section Implicitly-declared default constructor.

The compiler creates a default destructor for us if we do not write our own destructor in class. The default destructor works fine unless we have dynamically allocated memory or pointer in class. When a class contains a pointer to memory allocated in class, we should write a destructor to release memory before the class instance is destroyed. This must be done to avoid Memory Leak.

Since C++11, smart pointers are here for that. More generally, RAII solves this kind of issues. See en.cppreference.com/w/cpp/language...

Collapse
 
komalsingh1 profile image
Komal Singh

Thanks a lot, Pierre!! I never came across Move Constructor, Got this know this because of you. Thank you so much!

Collapse
 
pgradot profile image
Pierre Gradot

You don't use them everyday, don't worry ;)

They are part of the move semantic that was introduced with C++11. This is not something easy but it can increase performances in some situations.

Note that move constructor pairs with move assignment operator (just like copy ctor pairs with copy assignment operator).

You can check this link: thbecker.net/articles/rvalue_refer...