-6
class A {
public:
    A (int n = 0) : m_n(n) {}
    A (const A& a) : m_n(a.m_n) {}
private:
    int m_n;
}

or:

namespace std {
    template <class T1, class T2>
    struct pair {
        //type names for the values
        typedef T1 first_type;
        typedef T2 second_type;
        //member
        T1 first;
        T2 second;
        /* default constructor - T1 () and T2 () force initialization for built-in types */
        pair() : first(T1()), second(T2()) {}
        //constructor for two values
        pair(const T1& a, const T2& b) : first(a), second(b) {}
       //copy constructor with implicit conversions
        template<class U, class V>
        pair(const pair<U,V>& p) : first(p.first), second(p.second) {}
    };
    ....
}

I don't understand the constructors, copy constructor of these two classes. Please explain for me what does the part ": m_n(n)" do?

Linh Dao
  • 1,305
  • 1
  • 19
  • 31

1 Answers1

1
A (int n = 0) : m_n(n) {}
//           ^^^^^^^^^^

It is called the member-initialization-list.

In the definition of a constructor of a class, it specifies initializers for direct and virtual base subobjects and non-static data members.

For example in:

A (int n = 0) : m_n(n) {}

Here, your constructor of the A class initializes m_n with n.

Take a look here.

Pierre Fourgeaud
  • 14,290
  • 1
  • 38
  • 62