A conversion constructor in C++ is a constructor that is used to convert an object of one class to an object of another class. It is typically used to create objects of a class from objects of related classes, such as classes that have a common base class or are part of a type hierarchy.
A conversion constructor is defined with a single parameter of the type to be converted. For example:
class MyRectangle {
private:
int width;
int height;
public:
MyRectangle(int width, int height) : width(width), height(height) {}
MyRectangle(const MyRectangle& other) : width(other.width), height(other.height) {}
explicit MyRectangle(int side) : width(side), height(side) {}
int area() { return width * height; }
};
class MySquare : public MyRectangle {
public:
MySquare(int side) : MyRectangle(side, side) {}
explicit MySquare(const MyRectangle& rect) : MyRectangle(rect) {}
};
In this example, "MyRectangle" has a constructor that takes two parameters, "width" and "height" and a copy constructor, and "MySquare" has two constructors, one that takes one parameter, "side", and another that takes a MyRectangle object as a parameter. The second constructor of MySquare is a conversion constructor which creates a MySquare object from a MyRectangle object.
MyRectangle myRectangle(3,4);
MySquare mySquare(myRectangle);
In this example, myRectangle is created with the constructor that takes two parameters and mySquare is created with the conversion constructor, which creates a MySquare object from a MyRectangle object.
In summary, a conversion constructor in C++ is a constructor that is used to convert an object of one class to an object of another class. It is typically used to create objects of a class from objects of related classes. Conversion constructors are defined with a single parameter, which is of a different type than the class. They allow implicit conversion between types and can be used to convert an object of one class to an object of another class.
Comments
Post a Comment