Empty constructor in c++

蹲街弑〆低调 提交于 2019-12-23 04:34:06

问题


Well I understand the part that I will be getting some random value, but is theFoo() constructor in the snippet acting just like the default public constructor which the compiler supplies when we have no constructor defined?

#include<iostream>
using namespace std ;

class Foo{
        int i  ;
    public:
        Foo(){
        }
        void disp(){
            cout<<"i = "<<i  ;
        }
};

int main(){
    Foo bar1,bar2 ;
    bar1.disp();
    cout<<"\n";
    bar2.disp();
}

I have seen some people writing an empty constructor like this, but I could't understand exactly why/when is it to be used?


回答1:


A user-defined ctor without arguments, without ctor-init-list and with an empty body behaves nearly the same as the default-ctor.
There is one difference though, it does not count as a trivial ctor, ever!

Explicitly defaulting like this instead would avoid that difference and the concomittant potential performance-degradation:

Foo() = default; // Needs C++11

What does "default" mean after a class' function declaration?

See also <type_traits> for the easy way to detect the difference: http://en.cppreference.com/w/cpp/types/is_constructible




回答2:


An empty constructor is required for each class. If you want to have a constructor with initialization logic, you can add it along with the empty constructor. In some languages, if you do not write an empty constructor explicitly, compiler will generate it for you.

If is just to create an instance of a class and it does nothing else.

You can overload it with parameters to have another constructor that initializes its properties.




回答3:


When you provide the definition of an empty constructor, compiler does not provide the default constructor and initialize its own way to the members. You are just not allowing compiler to do its default initializations.



来源:https://stackoverflow.com/questions/25873281/empty-constructor-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!