{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

Explicit - class A public explicit A(int void f(A void g A...

Info icon This preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
Explicit In C++ it is possible to declare constructors for a class, taking a single parameter, and use those constructors for doing type conversion. For example: class A { public: A(int); }; void f(A) {} void g() { A a1 = 37; A a2 = A(47); A a3(57); a1 = 67; f(77); } A declaration like: A a1 = 37; says to call the A(int) constructor to create an A object from the integer value. Such a constructor is called a "converting constructor". However, this type of implicit conversion can be confusing, and there is a way of disabling it, using a new keyword "explicit" in the constructor declaration:
Image of page 1

Info icon This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document Right Arrow Icon
Image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: class A { public: explicit A(int); }; void f(A) {} void g() { A a1 = 37; // illegal A a2 = A(47); // OK A a3(57); // OK a1 = 67; // illegal f(77); // illegal } Using the explicit keyword, a constructor is declared to be "nonconverting", and explicit constructor syntax is required: class A { public: explicit A(int); }; void f(A) {} void g() { A a1 = A(37); A a2 = A(47); A a3(57); a1 = A(67); f(A(77)); } Note that an expression such as: A(47) is closely related to function-style casts supported by C++. For example: double d = 12.34; int i = int(d);...
View Full Document

{[ snackBarMessage ]}

What students are saying

  • Left Quote Icon

    As a current student on this bumpy collegiate pathway, I stumbled upon Course Hero, where I can find study resources for nearly all my courses, get online help from tutors 24/7, and even share my old projects, papers, and lecture notes with other students.

    Student Picture

    Kiran Temple University Fox School of Business ‘17, Course Hero Intern

  • Left Quote Icon

    I cannot even describe how much Course Hero helped me this summer. It’s truly become something I can always rely on and help me. In the end, I was not only able to survive summer classes, but I was able to thrive thanks to Course Hero.

    Student Picture

    Dana University of Pennsylvania ‘17, Course Hero Intern

  • Left Quote Icon

    The ability to access any university’s resources through Course Hero proved invaluable in my case. I was behind on Tulane coursework and actually used UCLA’s materials to help me move forward and get everything together on time.

    Student Picture

    Jill Tulane University ‘16, Course Hero Intern