Other constructors
#include <iostream>
using namespace std;
class Example {
public:
// 1. Default Constructor
Example()
{
cout << "Initialize members with default values" << endl;
}
// 2. Parameterized Constructor
Example(int a, double b) : member_a(a), member_b(b)
{
cout << "Initialize members with provided values" << endl;
}
// 3. Copy Constructor
Example(const Example &other) : member_a(other.member_a), member_b(other.member_b)
{
cout << "Create a new object as a copy of an existing object" << endl;
}
// 4. Move Constructor
Example(Example &&other) noexcept
: member_a(std::move(other.member_a)), member_b(std::move(other.member_b))
{
cout << "Transfer ownership of resources from one object to another" << endl;
}
// 5. Delegating Constructor
Example(int a) : Example(a, 0.0)
{
cout << "Delegate to the two-parameter constructor" << endl;
}
// 6. Converting Constructor
explicit Example(double d) : member_a(static_cast<int>(d)), member_b(d)
{
cout << "Convert from another type (in this case, double)" << endl;
}
// 7. Copy-List-Initialization Constructor
Example(std::initializer_list<int> list)
{
cout << "Initialize from a list of values" << endl;
}
private:
int member_a;
double member_b;
};
int main() {
// Usage examples:
Example e1; // Default constructor
Example e2(10, 3.14); // Parameterized constructor
Example e3 = e2; // Copy constructor
Example e4 = std::move(e3); // Move constructor
Example e5(5); // Delegating constructor
Example e6 = Example(3.14); // Converting constructor
Example e7 = {1, 2, 3, 4}; // Copy-list-initialization constructor
return 0;
}Last updated