Hello ladies and gents,
Ive been reading about Virtual Function in my book and there is this programming that shows how and what happens, I understand what is happening but one thing that came to my mind is that, previously in my book, there was mentioned that you should allways "delete" the memory that was allocated with "new". However, this is not done in this program and I understand why, it's just a small program to show the virtual function.
Still, I was wondering how one would do this as the memory allocation is done for an Array of Mammals :?:
#include <iostream>
class Mammal
{
public:
Mammal():itsAge(1) {}
~Mammal() {}
virtual void Speak() const { std::cout<<"Mammal speak!\n";}
protected:
int itsAge;
};
class Dog : public Mammal
{
public:
void Speak() const { std::cout<<"Woof!\n";}
};
class Cat : public Mammal
{
void Speak() const { std::cout<<"Meow!\n";}
};
class Horse : public Mammal
{
void Speak() const { std::cout<<"Hihihi!\n";}
};
class Pig : public Mammal
{
void Speak() const { std::cout<<"Oinkoink!\n";}
};
int main()
{
Mammal *theArray[5];
Mammal *ptr;
int choice, i;
for( i = 0; i < 5; i++)
{
std::cout<<"(1)dog (2)cat (3) horse (4) pig: ";
std::cin>> choice;
switch(choice)
{
case 1:
ptr = new Dog;
break;
case 2:
ptr = new Cat;
break;
case 3:
ptr = new Horse;
break;
case 4:
ptr = new Pig;
break;
default:
ptr = new Mammal;
break;
}
theArray[i] = ptr;
}
for( i = 0; i < 5; i++)
theArray[i]->Speak();
return 0;
}
As you can see, depending on wich number you enter, memory is allocated for a certain class function, however, all memory is allocated into theArray, so I tried the following
for( i = 0; i < 5; i++)
delete [i] theArray;
But, this is giving me the following error:
warning C4154: deletion of an array expression; conversion to pointer supplied
Can any of you help me out here, thanks :)