So I recently started to study about structures and came across constructors and destructors. Can somebody explain to me what the point of them are? Any small basic coding examples would be great.
Constructors are called everytime you make an instance of a class. (in C++, a struct is only a class that has its members public by default). Constructors must be public and have the class name. They are mainly used to initialize values for the class, but can also to initialize instances via copying and moving.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include<iostream>
class object
{
public:
object(constint & val): value(val)
{
std::cout<<"An instance of the object class has been made. Constructor has been called.";
}
private:
int value;
};
int main(void)
{
object my_object(10);
return 0;
}
Output
An instance of the object class has been made. Constructor has been called.