i'm learning how to make classes and i want to prevent my user from creating an object without providing a variable. The problem is that i don't know how to procede in order to do that. here's my code :
class KoalaNurse {
public:
int id; // the var that i need to provide in order to create a new object if it's not provided it wont create the object
void giveDrug(std::string gato, SickKoala *patient) {
patient->takeDrug(gato);
}
~KoalaNurse() {
std::cout << "Nurse " << id << ": Finally some rest !" << std::endl;
}
};
ty for any help !
CodePudding user response:
You need to define your own constructor in order for the compiler not to create the default one.
KoalaNurse (int some_value)
{
//your code
};
Another option is to use keyword delete
in order to prevent creating default constructor:
KoalaNurse() = delete;
CodePudding user response:
In a situation like this you want to provide a user defined constructor.
class KoalaNurse {
public:
explicit KoalaNurse( int id )
: id_{ id }
{ }
private:
int id_;
};
int main( ) {
KoalaNurse nurse{ 10 };
}
With a constructor, in order to instantiate your class
you have to provide an id
.