Michael Schäfer
Michael Schäfer

Reputation: 57

virtual functions segmentation fault

I want to learn virtual functions. I have made print() in class Base virtual and my program crashes. Why do I have to create the two objects with new?

#include <iostream>

class Base {
    public:
        virtual void print();
};

void Base::print() {
    std::cout << "Base print method" << std::endl;
}

class Derived : public Base {
    public:
        void print();
};

void Derived::print() {
    std::cout << "Derived print method" << std::endl;
}

int main()
{
    Base* b; // Base* b = new Base(); runs
    b->print();
    Derived* d; // Derived *d = new Derived(); runs
    d->print();
}

Upvotes: 0

Views: 668

Answers (4)

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 122133

Why do I have to create the two objects with new?

You don't have to.

It is a common misunderstanding that you need to dynamically create objects for polymorphism. Often polymorphism is used with dynamically created objects, but it is not strictly necessary to enable polymorphism. You need references or pointers for polymorphism, so eg this will work:

#include <iostream>

class Base {
    public:
        virtual void print();
};

void Base::print() {
    std::cout << "Base print method" << std::endl;
}

class Derived : public Base {
    public:
        void print();
};

void Derived::print() {
    std::cout << "Derived print method" << std::endl;
}

void do_print(Base& b) {
   b.print();
}    

int main()
{
    Base b;
    do_print(b);
    Derived d;
    do_print(d);
}

In your code you have only pointers in main but you never create objects. Your pointers do not point to objects, the are uninitialized. Dereferencing those pointers invokes undefined behavior.

Upvotes: 1

GazTheDestroyer
GazTheDestroyer

Reputation: 21241

You are using pointers, so they need to point to something.

You're basically saying: "hey, this b variable points to a Base object", but you never create a base object (with new), so it points to random memory, and crashes when you try and treat that memory as a Base object.

Upvotes: 0

Bathsheba
Bathsheba

Reputation: 234635

Base* b; doesn't create an object, but creates a pointer of type Base* with automatic storage duration. The behaviour on dereferencing that pointer is undefined.

Base b or new Base() actually create objects. The former has automatic storage duration, the latter has dynamic storage duration.

Upvotes: 0

po.pe
po.pe

Reputation: 1162

Because Base* b does not create the object as long as you don't tell it to do so by adding the new Base(). Therefore dereferencing your pointer to the print function has no valid target.

Upvotes: 0

Related Questions