简体   繁体   中英

why does my class only work with two constructors c++

This does not work

When I don't have a blank constructor in my class the code will not run causing an error saying no default constructor exists for class.

#include <iostream>

class myClass
{
public:
    myClass(int val)
        :x(val)
    {}


private:
    int x;
};

int main()
{
    myClass random;
    return 0;
}

This works

#include <iostream>

class myClass
{
public:
    myClass(int val)
        :x(val)
    {}

    myClass()
    {}

private:
    int x;
};

int main()
{
    myClass random;
    return 0;
}

This is because when you try to instantiate the object myClass random , you are trying to invoke the default constructor which you do not have.

If you changed it to myClass random(3) ( basically trying to invoke the constructor that you have), you would see that the compiler would have no problems.

If you want myClass random to compile fine, then you must have a default constructor in your class.

Once you declare a constructor in a class (any constructor), the compiler won't automatically generate a default constructor for you (this is what you're calling the blank constructor).

If you don't want to implement the default constructor (generally a good idea if you just want the default behavior), you can tell the compiler to generate it for you as of C++11.

class myClass {
public:
    myClass(int val)
        :x(val)
    {}

    myClass() = default; // the compiler handles the implementation

private:
    int x;
};

In the first case you have defined a parameterized constructor. When a constructor is defined the compiler now does not automatically define a default constructor like before.

If no constructor is defined the compiler automatically defines a default constructor but if another constructor is defined the compiler will not do so.

ie in first case a default constructor does not exist. In the second case you have defined one and hence has no errors.

See default constructor .

If no user-declared constructors of any kind are provided for a class type, the compiler will always declare a default constructor as an inline public member of its class.

However, there's a constuctor declared in your class, thus the compiler won't declare a default constructor. You have to explicitly declare one yourself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM