Skip to content

Instantly share code, notes, and snippets.

@mastbaum
Created June 2, 2011 16:37
Show Gist options
  • Save mastbaum/1004764 to your computer and use it in GitHub Desktop.
Save mastbaum/1004764 to your computer and use it in GitHub Desktop.
An overview of weird automatic overloading of C++ constructors
#include<iostream>
/** C++ does some strange stuff with constructors. Having default values makes
* sense, but they've added some weird, unintuitive shorthand that's just an
* accident waiting to happen:
*
* MyClass c = MyClass(5) <--> MyClass c = 5
*
* where in both cases 5 is taken as the first argument. In both cases, it will
* do whatever casting is needed and allowed.
*
* What weirds me out is that this syntax is specific to single-argument
* constructors. You could pull this in Python (MyClass c = 1, 2, 3)...
*/
class Foo
{
public:
Foo(int a=42, int b=21) { fA=a; fB=b; }
int fA, fB;
};
int main(int argc, char* argv[])
{
// 1. use the defaults
Foo foo1;
std::cout << "foo1: " << foo1.fA << " " << foo1.fB << "\n";
// 2. call the constructor explicitly
Foo foo2 = Foo(1,2);
std::cout << "foo2: " << foo2.fA << " " << foo2.fB << "\n";
// 3. call the constructor with 1 arg
Foo foo3 = Foo(5);
std::cout << "foo3: " << foo3.fA << " " << foo3.fB << "\n";
// 4. c++ does the same thing as (3)
Foo foo4 = 5;
std::cout << "foo4: " << foo4.fA << " " << foo4.fB << "\n";
// 5. c++ invents an operator= for us...
Foo foo5 = foo4;
std::cout << "foo5: " << foo5.fA << " " << foo5.fB << "\n";
// ... which copies ...
std::cout << "foo5 @ " << &foo5 << ", foo4 @ " << &foo4 << "\n";
// which is different from pointer assignment:
Foo* fooPtr1 = new Foo(3);
Foo* fooPtr2 = fooPtr1;
std::cout << "fooPtr1: " << fooPtr1->fA << " " << fooPtr1->fB << "\n";
std::cout << "fooPtr2: " << fooPtr2->fA << " " << fooPtr2->fB << "\n";
std::cout << "fooPtr1 @ " << fooPtr1 << ", fooPtr2 @ " << fooPtr2 << "\n";
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment