I wanna understand about the new operator in C++ and what's going on my code. I have 2 files A and B,both can be compiled.But I'm facing the error "Segmentation fault" when running binary of A.Binary of B is working fine.
What does the "new" operator do in file B ?
File A
#include <iostream>
using namespace std;
class Animal
{
public:
virtual void eat() { std::cout << "I'm eating generic food."<< endl; }
};
class Cat : public Animal
{
public:
void eat() { std::cout << "I'm eating a rat." << endl;}
};
void func(Animal *xyz){
xyz->eat();
}
int main()
{
Animal *animal ;
Cat *cat ;
func(animal);
func(cat);
return 0;
}
File B
#include <iostream>
using namespace std;
class Animal
{
public:
virtual void eat() { std::cout << "I'm eating generic food."<< endl; }
};
class Cat : public Animal
{
public:
void eat() { std::cout << "I'm eating a rat." << endl;}
};
void func(Animal *xyz){
xyz->eat();
}
int main()
{
Animal *animal = new Animal;
Cat *cat = new Cat;
func(animal);
func(cat);
return 0;
}
The differences between file A and B are
Animal *animal = new Animal;
Cat *cat = new Cat;