Y
yashwant pinge
The following program is related to template...
include <iostream>
using namespace std;
template<class T, int size = 100>
class Array
{
T array[size];
public:
T& operator[](int index)
{
cout<<"Array:--"<<endl;
return array[index];
}
int length() const { return size; }
};
class Number
{
float f;
public:
Number(float ff = 0.0f) : f(ff)
{
cout<<"NUMBER CONST..."<<endl;
}
Number& operator=(const Number& n)
{
cout<<"NUMBER:--"<<endl;
f = n.f;
return *this;
}
operator float() const
{
return f;
}
friend ostream& operator<<(ostream& os, const Number& x)
{
return os << x.f;
}
};
template<class T, int size = 2>
class Holder
{
Array<T, size>* np;
public:
Holder() : np(0) {
cout<<"HOLDER CONST..."<<endl;
}
T& operator[](int i)
{
cout<<"HOLDER:--"<<endl;
if(!np) np = new Array<T, size>;
cout<<"AFTER ALLOCATION..."<<endl;
return np->operator[](i);
}
int length() const
{
return size;
}
~Holder() { delete np; }
};
int main()
{
Holder<Number> h;
for(int i = 0; i < 2; i++)
{
h = i;
}
for(int j = 0; j < 2; j++)
cout << h[j] << endl;
} ///:~
output:
HOLDER CONST...
NUMBER CONST...
HOLDER:--
NUMBER CONST...
NUMBER CONST...
AFTER ALLOCATION...
Array:--
NUMBER:--
NUMBER CONST...
HOLDER:--
AFTER ALLOCATION...
Array:--
NUMBER:--
HOLDER:--
AFTER ALLOCATION...
Array:--
0
HOLDER:--
AFTER ALLOCATION...
Array:--
1
I want to know the working or flow of this program as per the output
that i have mentioned above.
Yashwant
include <iostream>
using namespace std;
template<class T, int size = 100>
class Array
{
T array[size];
public:
T& operator[](int index)
{
cout<<"Array:--"<<endl;
return array[index];
}
int length() const { return size; }
};
class Number
{
float f;
public:
Number(float ff = 0.0f) : f(ff)
{
cout<<"NUMBER CONST..."<<endl;
}
Number& operator=(const Number& n)
{
cout<<"NUMBER:--"<<endl;
f = n.f;
return *this;
}
operator float() const
{
return f;
}
friend ostream& operator<<(ostream& os, const Number& x)
{
return os << x.f;
}
};
template<class T, int size = 2>
class Holder
{
Array<T, size>* np;
public:
Holder() : np(0) {
cout<<"HOLDER CONST..."<<endl;
}
T& operator[](int i)
{
cout<<"HOLDER:--"<<endl;
if(!np) np = new Array<T, size>;
cout<<"AFTER ALLOCATION..."<<endl;
return np->operator[](i);
}
int length() const
{
return size;
}
~Holder() { delete np; }
};
int main()
{
Holder<Number> h;
for(int i = 0; i < 2; i++)
{
h = i;
}
for(int j = 0; j < 2; j++)
cout << h[j] << endl;
} ///:~
output:
HOLDER CONST...
NUMBER CONST...
HOLDER:--
NUMBER CONST...
NUMBER CONST...
AFTER ALLOCATION...
Array:--
NUMBER:--
NUMBER CONST...
HOLDER:--
AFTER ALLOCATION...
Array:--
NUMBER:--
HOLDER:--
AFTER ALLOCATION...
Array:--
0
HOLDER:--
AFTER ALLOCATION...
Array:--
1
I want to know the working or flow of this program as per the output
that i have mentioned above.
Yashwant