Skip to content

Instantly share code, notes, and snippets.

@vakho10
Last active July 22, 2017 12:12
Show Gist options
  • Save vakho10/b94a7a72bfddddfd57ceee066dc1dbd1 to your computer and use it in GitHub Desktop.
Save vakho10/b94a7a72bfddddfd57ceee066dc1dbd1 to your computer and use it in GitHub Desktop.
// In C++, a constructor with only one required parameter is considered an implicit conversion function.
// It converts the parameter type to the class type.
// Whether this is a good thing or not depends on the semantics of the constructor.
#include <iostream>
#include <string>
using namespace std;
class Foo
{
public:
// single parameter constructor, can be used as an implicit conversion
explicit Foo(int foo) : m_foo(foo)
{
cout << "int Foo object constructed with foo input " << foo << endl;
}
// Can be auto constructed by compiler at compile time
// (works only for single argument constructors)
Foo(string foo) : s_foo(foo)
{
cout << "string Foo object constructed with foo input " << foo << endl;
}
int GetFoo() { return m_foo; }
private:
int m_foo;
string s_foo;
};
// Here's a simple function that takes a Foo object:
void DoBar(Foo foo)
{
int i = foo.GetFoo();
}
// and here's where the DoBar function is called.
int main()
{
DoBar(42); // Compiler error because of 'explicit' keyword
DoBar(string("A")); // No probs
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment