简体   繁体   中英

c++ is default constructor called in parametrized constructor?

I have the following template class:

template<typename T, int nSize> class Stack{
private:
    int m_nCurrentPos;
    Array<T> m_tArray;
public:
    Stack(int nCurrentPos = 0);
    ...
};

I would like the default constructor work as follows:

template<typename T, int nSize> Stack<T,nSize>::Stack(int nCurrent){ 
    m_nCurrent = nCurrentPos;
    m_tArray = Array<T>::Array(nSize);
};

Where Array looks like that:

template <typename T> class Array{
private:
    T* m_cData;
    int m_nSize;
    static int s_nDefaultSize;
public:
    Array();
    Array(int nSize);
    ...
};

And its constructors are:

template<typename T> Array<T>::Array(){
    m_nSize = s_nDefaultSize;
    m_cData = new T[m_nSize];
}

and, obviously,

template<typename T> Array<T>::Array(int nSize){
    m_nSize = nSize;
    m_cData = new T[m_nSize];
}

So, Stack is composed from Array and some extra functionalities. My problem is that when in Array I define s_nDefaultSize to be say 512 , and I try to instantiate Stack<int,1024> I'm getting an exception from class Array, saying that I'm trying to assign two arrays of different length. As soon as I change the code such that s_nDefaultSize=1024 (so it matches the template's non-type argument nSize ), everything's fine. So, in other words, the exception occurs as soon as s_nDefaultSize != nSize . So, my guess is that in the code above, in the default constructor of Stack<T,nSize> , ie, m_tArray = Array<T>::Array(nSize); the m_tArray is created by default constructor of Array (employing s_nDefaultSize ) and only then the compiler tries to assign it to Array<T>::Array(nSize) (employing my nSize value). Is that correct? And if yes, how can I change this behaviour? This is another question that I posted yesterday, which, even though is about inheritance, not composition, is very much related to the question in this thread. Cheers!

You need to use a member initialization list with the constructor of Stack :

template<typename T, int nSize>
Stack<T,nSize>::Stack(int nCurrent)
  : m_tArray(nSize)
{ 
    m_nCurrent = nCurrentPos;
};

As you have it, m_tArray will first be default constructed and then assigned to in your constructor. Here, we use the member initialization list to initialize m_tArray to the right size immediately.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM