panJames
asked on
Template, pointer initialization
Hello experts,
please have a look at the code attached.
It does not compile...
Could you please tell me why?
Thank you
panJames
please have a look at the code attached.
It does not compile...
Could you please tell me why?
Thank you
panJames
# include <iostream>
using namespace std;
class Animal
{
int age;
public:
Animal() : age(10){};
int AgeGet()
{
return age;
}
};
template <class T>
class Zoo
{
private:
T * pObj;
int length;
public:
T & operator[] (int index)
{
return pObj[index];
}
Zoo() : length(12)
{
pObj = new T[12]; //container for Animals
for (int i = 0; i < 12; i++)
{
pObj[i] = 0; //pointer initialization, it does not point at any object
//xxxxxxxxxxxxxxxxxxxxx compiler crashes here xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
}
}
};
int main()
{
Zoo<Animal> zoo; //it creates 12 spaces for objects
Animal * animal = new Animal;
cout << animal -> AgeGet();
zoo[0] = *animal;
delete animal;
cout << zoo[0].AgeGet();
return 0;
}
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.