tags:

views:

316

answers:

4

I apologize in advance, my C++ is rusty...

What does

: m_nSize(sizeof(t1))

mean in the following 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 that an alternative syntax?

Thanks!

+9  A: 

It has nothing todo with copy ctor. You are initializing the variable m_nSize using initializer list with the sizeof the template argument t1.

Naveen
+3  A: 

There is no way to initialize a member variable directly in the class defination. This is called initialization list. You can imagine it to be something like:

const int m_nSize = sizeof(t1);

C++0x allow the above form by the way.

AraK
+1  A: 

CTypeSize(const T &t1) is the constructor of the class. Members of the class can be initialised 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 initialised with the value of sizeof(t1).

+1  A: 

Your question is double:

The : member( value ) syntax initializes a new object's member to value.

But template< typename T> Class( const T& ) is not the copy constructor. That one 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); }

Will result in the template constructor to be called, followed by the 'synthesized' copy constructor (will output just "T".)

When you insert the copy constructor explicitly, that one will be called (output will be "TC").

xtofl