I'm new to C++, and am used to working with Java. In Java, I have the option of declaring an object without instantiating it, and would like to do the same in C++.
Assuming there is some class Foo, in Java I could write Foo bar; to declare an instance of Foo without initializing bar. However, in C++ when I write Foo bar;, bar is initialized by calling the default constructor of class Foo.
This is particularly vexing if I have written one or more constructors for class Foo, each of which have at least one argument. In this case, the code will fail to compile with an error similar to no matching function for call to 'Foo::Foo()'
For example, say I have the following class definition in Java:
public class Foo { private boolean b; Foo(boolean b) { this.b = b; } } and the corresponding class definition in C++:
class Foo { bool b_; public: Foo(bool b) : b_(b) {} }; In Java, I could write some method
public static Foo makeFoo(int x) { Foo result; if (x > 10) { result = new Foo(true); } else { result = new Foo(false); } return result; } However, if I write a similar method in C++, I get a compilation error:
Foo makeFoo(int x) { Foo result; // here, a call is made to Foo::Foo() which doesn't exist, and thus compilation fails if (x > 10) { result = Foo(true); // this would probably also fail since I didn't specify a copy-constructor, but I'm not entirely sure } else { result = Foo(false); // as above, I think this would probably fail } return result; } While the example I gave is useless, I frequently used this sort of approach when writing Java code. Is there a way to emulate this behavior in C++? Alternatively, is this just bad design? If so, what sort of approach would you recommend?
Foo bar;in Java is roughly equivalent toFoo* bar = nullptr;in C++, or perhapsstd::unique_ptr<Foo> bar;. Read about (smart) pointers in your favorite C++ textbook.nullis a safe default for an object reference. Without calling the default constructor, the bit pattern that corresponds to (say) astd::stringfield might be arbitrary stack garbage. How would you defend against that?null). Similarly toint x;. You don't have to init them in C++, however.Foo result(x > 10);. Do you have a need to call different constructors based on some condition? (There are methods to do things. Which method is appropriate depends on your needs.)