I'm new to OOP programming and C++ (did a little java first), and I came across a problem I do not understand. I basically try to use polymorphism and use the virtual function to call the derived function on the base *
I Why does this break when adding the commented line?
#include <iostream>
class Base
{
public:
Base() { std::cout << "Base constructor.\n"; }
virtual ~Base() { std::cout << "Base destructor.\n"; }
virtual void foo() { std::cout << "Base::foo()\n"; }
};
class Derived : public Base
{
// std::string d_str;
public:
Derived() { std::cout << "Derived constructor.\n"; }
~Derived() { std::cout << "Derived destructor.\n"; }
void foo() { std::cout << "Derived::foo()\n"; }
};
int main(int argc, char const *argv[])
{
Base *ptr = new Derived[3];
(*ptr).foo();
(ptr + 1)->foo();
(ptr + 2)->foo();
delete[] ptr;
}
It would be great if someone could help me with this!