Avatar of panJames
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

# 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;

}

Open in new window

C++

Avatar of undefined
Last Comment
sarabande

8/22/2022 - Mon
SOLUTION
phoffric

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
ASKER CERTIFIED SOLUTION
Orcbighter

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
SOLUTION
Log in to continue reading
Log In
Sign up - Free for 7 days
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes