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();
}
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.