vendredi 11 août 2023

The compiler creates a constructor of N args when I have N public member variables and no private ones. What is happening here?

The following code compiles and runs as expected, unless I uncomment one of the two commented out lines that I have labelled with "prevents compilation":

#include <string>
#include <iostream>

class Animal {
    public:
    int count;
    std::string foobar;
    //Animal() = delete; // prevents compilation

    void squeak() const {
        std::cout << count << ". Squeak from " << foobar << std::endl;
    }
    private:
    //int priv; // prevents compilation
};

int main() {  
    std::string foo{"foo"};
    Animal mouse(1, foo);
    //Animal mouse{1, foo};
    //Animal mouse{1, foo, 3};
    mouse.squeak();
    std::cout << "\n";
}

What is happening regarding constructors here, what is this mechanism called and when should one use it?

Aucun commentaire:

Enregistrer un commentaire