-1

Is it possible to do something like

Class obj="";

Can use "" to initialize an object? I saw this in an interview, and the interviewer mentioned it is valid.

Update: Thanks for the answers here. For the benefit of future readers, I did some search, this is called copy constructor. Some links like copy constructor parameters could be useful.

Community
  • 1
  • 1
william007
  • 17,375
  • 25
  • 118
  • 194

1 Answers1

1

Yes, it really is valid. Here is an example code where it works:

#include <iostream>
#include <string>

using namespace std;

class Class {
private:
    string data;
public:
    Class (const char* foo) {
        data = foo;
    }
};

int main()
{
    Class foo="bar";

    return 0;
}
Andros Rex
  • 372
  • 1
  • 7
  • In such a case, why we use Class foo=new Class("bar"); appear to have compilation error? – william007 Jul 04 '16 at 01:51
  • @william007 It's because "new Class(...)" returns a pointer, so it should be Class *foo = new Class("bar"). Also, if you didn't want a pointer, it should be Class foo = Class("bar") or Class foo("bar") or Class foo="bar". Either one of these works. – Andros Rex Jul 04 '16 at 01:53
  • Thanks Andros, can the format `Class foo="bar"` support >=2 constructor arguments? – william007 Jul 04 '16 at 01:59
  • @william007 Surely not. And if it did, it would look ugly (at least to me), so I'd stick to the brackets. – Andros Rex Jul 04 '16 at 02:09
  • @william007 It looks like you should start [here](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – molbdnilo Jul 04 '16 at 07:54