C++ examples for Class:Constructor
A class constructors with a single parameter can be implicit casted from the type of the parameter to the class type.
#include <iostream> class Cube {/*from w w w . j ava 2s . c o m*/ public: double side; Cube(double side); // Constructor double volume(); // Calculate volume of a cube bool compareVolume(Cube aCube); // Compare volume of a cube with another }; Cube::Cube(double len) : side {len} { std::cout << "Cube constructor called." << std::endl; } double Cube::volume() { return side*side*side; } bool Cube::compareVolume(Cube aCube) { return volume() > aCube.volume(); } // Problems of implicit object conversions int main() { Cube pool1 {7.0}; Cube pool2 {3.0}; if(pool1.compareVolume(pool2)) std::cout << "pool1 is larger than pool2." << std::endl; else std::cout << "pool1 is less than or equal to pool2." << std::endl; std::cout << "volume of pool1 is" << pool1.volume() << std::endl; if(pool1.compareVolume(50.0)) std::cout << "Volume of pool1 is greater than 50" << std::endl; else std::cout << "Volume of pool1 is less than or equal to 50" << std::endl; }
The code the compiler produces is equivalent to:
if(pool1.compareVolume(Cube {50.0})) std::cout << "Volume of pool1 is greater than 50" << std::endl; else std::cout << "Volume of pool1 is less than or equal to 50" << std::endl;
You can prevent this nightmare from happening by declaring the constructor as explicit:
class Cube { public: double side; explicit Cube(double side); // Constructor double volume(); // Calculate volume of a cube bool compareVolume(Cube aCube); // Compare volume of a cube with another };