开发者

A c++ syntax question: class for method

in the code below, it has the 开发者_StackOverflow社区following line

 base_list(const base_list &tmp) :memory::SqlAlloc()

base_list is a method, memory is a namespace, SqlAlloc is a class, so what does it mean when combine them together?

class base_list :public memory::SqlAlloc
{
public:
  base_list(const base_list &tmp) :memory::SqlAlloc()
  {
    elements= tmp.elements;
    first= tmp.first;
    last= elements ? tmp.last : &first;
  }


base_list(const base_list &tmp) :memory::SqlAlloc() 

Uses Initializer list to call constructor of class SqlAlloc inside namespace memory.

For more information on advantages of using Initializer List in C++, See this.


It calls the default constructor of the base class memory::SqlAlloc().

namespace memory {

class SqlAlloc
{
public:
    SqlAlloc() {} // SqlAlloc's default constructor
};

}

//...

class base_list : public memory::SqlAlloc
{
public:
  // base_list constructor
  base_list(const base_list &tmp) : memory::SqlAlloc()
  {
   // The code after the ":" above and before the "{" brace
   // is the initializer list
    elements= tmp.elements;
    first= tmp.first;
    last= elements ? tmp.last : &first;
  };

Consider the following:

int main()
{
    base_list bl; // instance of base_list called "bl" is declared.
}

When bl is created, it calls the constructor of base_list. This causes the code in the initializer list of the base_list constructor to run. That initializer list has memory::SqlAlloc(), which calls SqlAlloc's default constructor. When SqlAlloc's constructor finishes, then the base_list's constructor is run.


base_list is the constructor and it's calling the constructor of the base class (SqlAlloc).


:memory::SqlAlloc() calls the base class's default contructor and is as such not required here;

The syntax is called: (base) initializer list, see also Difference between initializer and default initializer list in c++


base_list inherits from memory::SqlAlloc.

The line you ask about is the copy constructor. The : memory::SqlAlloc() after is the base class initializer. It calls the constructor of the base class.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜