-8

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;
Sagar V
  • 11,083
  • 7
  • 41
  • 62
Nam Pham
  • 196
  • 6
  • 2
    When you define local variables in C++, like e.g. `animal` or `cat` in your examples, they are not automatically initialized but will have an *indeterminate* value. Using them in any way without initialization leads to *undefined behavior*. In the case of a pointer, it means it will point to a seemingly random location. – Some programmer dude Jun 13 '17 at 05:42
  • 2
    This is a very basic question... Read a book or Google it. – user253751 Jun 13 '17 at 06:01
  • 2
    You are missing the basic very concept of what pointers are and do. – eddie Jun 13 '17 at 06:07
  • I do not want to explain. But because so many experts are here. I just started learning C ++ a few days ago. I will Google more before asking next time – Nam Pham Jun 13 '17 at 06:12
  • As you continue studying C++ many other questions and doubts will arise ;) – eddie Jun 13 '17 at 06:15

1 Answers1

1

The new operator allocates memory for the object and then invokes the constructor to initialize it. In file A you do not initialize your objects, thus passing uninitialized pointers to func, leading to the segmentation fault.

Mureinik
  • 252,575
  • 45
  • 248
  • 283
  • 5
    He don't pass nullpointer. The pointer are not initialized, so the value is random. He should use `Animal animal` and pass the address `&animal`, to use the `func()` without the new operator. – Andre Kampling Jun 13 '17 at 05:42
  • 1
    No, they're not null pointer. And the behavior is undefined. – songyuanyao Jun 13 '17 at 05:43