Object mode (3)---default constructor

Default Constructor

Which case will created 'default constructor' by compiler?

Four case:

1.The member object has a default constructor.

class Foo{ public Foo(), Foo(int )   };
class Bar { public Foo foo;char* str};

As you see below, class Bar need a default constructor to create the foo.

1.this will be created a default constructor with Bar();

2.the member value 'str' will not be inited.

 

2.devided class has no default class

class Bar
{
public:
    Bar(int index){};
    Foo foo;
    char* str;
};


class Bear:public Bar{
public:
    Foo foo;

};

this will report error:

DefaultConstructorDemo.cpp"
../src/DefaultConstructorDemo.cpp: In function ‘int main()’:
../src/DefaultConstructorDemo.cpp:15: error: no matching function for call to ‘Bar::Bar()’
../src/Foo.h:23: note: candidates are: Bar::Bar(int)
../src/Foo.h:21: note:                 Bar::Bar(const Bar&)
make: *** [src/DefaultConstructorDemo.o] 错误 1

there is no Bar::Bar function for class Bear default constructor to call.

3.has virtual function class

the default constructor must be created to add vptr.

4.virtual base class

class A;public virtual B{

};

like case 3;

Note:

Only below 4 case will create default constructor by compiler.

the value member will not inited by default constructor, it need to be inited by coder.And the member object will be called default constructor, if none ,will report error.

 

 

 

 

 

 

posted @ 2014-04-03 16:57  手机从业者  阅读(124)  评论(0)    收藏  举报