[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.c++

Why this work

abhisheksaksena1

11/26/2008 3:16:00 AM

I have following code:-

template<class T>
struct type
{
typedef T X;
type ():first(T()){}
T first; // the first stored value
};

struct coordinate
{
coordinate(unsigned i, unsigned j):x(i), y(j){}
unsigned x,y;
};

int main ()
{

type<coordinate *> p;

coordinate *third= p.first; //<---pointer third is initialized to
zero
}

How come here p.first is initialized to zero?

What T() for pointer means while initializing first? Does operator ()
defined for pointers?

Thanks
AS

2 Answers

Kai-Uwe Bux

11/26/2008 3:35:00 AM

0

abhisheksaksena1@gmail.com wrote:

> I have following code:-
>
> template<class T>
> struct type
> {
> typedef T X;
> type ():first(T()){}
> T first; // the first stored value
> };
>
> struct coordinate
> {
> coordinate(unsigned i, unsigned j):x(i), y(j){}
> unsigned x,y;
> };
>
> int main ()
> {
>
> type<coordinate *> p;
>
> coordinate *third= p.first; //<---pointer third is initialized to
> zero
> }
>
> How come here p.first is initialized to zero?

Because it is initialized by the value of the temporary T() where T is
coordinate*.


> What T() for pointer means while initializing first?

As per [5.2.3/2]:

The expression T(), where T is a simple-type-specifier (7.1.5.2) for a
non-array complete object type or the (possibly cv-qualified) void type,
creates an rvalue of the specified type, which is value-initialized
(8.5; no initialization is done for the void() case).

the pointer is value-initialized. For scalar types, such as coordinate*,
this means initialization by 0.


> Does operator () defined for pointers?

No.



Best

Kai-Uwe Bux

Andrey Tarasevich

11/26/2008 7:04:00 AM

0

abhisheksaksena1@gmail.com wrote:
> ...
> template<class T>
> struct type
> {
> typedef T X;
> type ():first(T()){}
> T first; // the first stored value
> };
>
> struct coordinate
> {
> coordinate(unsigned i, unsigned j):x(i), y(j){}
> unsigned x,y;
> };
>
> int main ()
> {
> type<coordinate *> p;
>
> coordinate *third= p.first; //<---pointer third is initialized to
> zero
> }
>
> How come here p.first is initialized to zero?

Because you initialized it yourself in 'type's constructor initializer list

...
type() : first(T()) // <- here
{}
...

> What T() for pointer means while initializing first?

It means a null-pointer value.

> Does operator () defined for pointers?

It is not an operator in this context. It is an initializer. And for
pointers it results in zero-initialization, which is why you get a
null-pointer in your case.

--
Best regards,
Andrey Tarasevich