Why this work

A

abhisheksaksena1

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
 
K

Kai-Uwe Bux

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
 
A

Andrey Tarasevich

...
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,166
Messages
2,570,907
Members
47,446
Latest member
Pycoder

Latest Threads

Top