Goldman Sachs Interview Question
Software Engineer / Developersin other cases compiler may create a trivial default constructor but that does not guarantee initialization of Data members.
I think whenever there is no user defined constructor(s), it is mandatory for the compiler to generate a default constructor. No?
I still dont get it. For example, in your first case, you mentioned "Since class FOO has a default constructor therefore compiler will synthesize the same for Bar class as well.
class FOO
{
int a;
public:
FOO() {};
}
class Bar
{
FOO f;
};
"
So you mean even if I add a non-default constructor for Bar, the compiler will still synthesize a default constructor? I dont think so.
Could you kindly point me to the related section in C++ Primer? Thanks.
Compiler synthesizes non trivial default constructors in following 4 cases only .
- RS February 14, 20111. If a Class has a member of another class and that class has a default constructor.
e.g. Since class FOO has a default constructor therefore compiler will synthesize the same for Bar class as well.
class FOO
{
int a;
public:
FOO() {};
}
class Bar
{
FOO f;
};
2. Compiler synthesizes constructor for Derived class if base class also has a derived class constructor.
3. Either of Base class or Derived class has virtual method in it.
4. class is inherited as virtual base class.