Reputation: 57
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
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
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
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
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