C ++ code constructor syntax
I apologize in advance, my C ++ is rusty ...
What is he doing
: m_nSize(sizeof(t1))
mean in the next section?
class CTypeSize
{
public:
template<class T>
CTypeSize(const T &t1) :
m_nSize(sizeof(t1))
{
}
~CTypeSize(void){ };
int getSize(void) const{ return m_nSize; }
private:
const int m_nSize;
};
I understand copy constructors, but I remember the syntax as Class :: Class (const Class & p). Am I thinking of something else or is this an alternative syntax?
Thank!
source to share
CTypeSize (const T & t1) is the constructor of the class. Class members can be initialized in the constructor.
class testclass {// constructor: a, b, c are set to // 0, 1, 2 testclass (): a (0), b (1), c (2) {}
int a, b, c; // members};
In your example: ": m_nSize (sizeof (t1))" means that m_nSize is initialized to sizeof (t1).
Your question is double:
The syntax : member( value )
initializes a new member of the object value
.
But template< typename T> Class( const T& )
it is not a copy constructor. This is Class( const Class& )
.
So
#include <iostream>
struct C {
template< typename T >
C( const T& t ) { std::cout << "T"; }
// C( const C& c ) { std::cout << "C"; }
};
int main() { C c1(1); C c2(c1); }
The template constructor will be called, followed by the "synthesized" copy constructor (only "T" will be output.)
When you insert a copy constructor explicitly, this call will be called (the output will be "TC").
source to share
There is one more important thing about declaring a member variable CTypeSize::m_nSize
. Have you noticed a modifier const
in this declaration?
class member-var declared as "const"
can only be initialized in the initialization list.
As AraK mentioned, in C ++ 11 const member-var can also be initialized with a const expression. This is a compile-time case, while an initialization list allows const member-var to be initialized at runtime.
source to share