Object mode (3)---default constructor

Default Constructoride

Which case will created 'default constructor' by compiler?this

Four case:spa

1.The member object has a default constructor.code

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.blog

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

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

 

2.devided class has no default classfunction

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


class Bear:public Bar{
public:
    Foo foo;

};

this will report error:class

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] 錯誤 1object

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.

相關文章
相關標籤/搜索