The following code compiles but gives segmentation error when I run it.I am using dynamic memory in the main using base class pointer to derived class object and that gives error when runs.
#include <iostream>
using namespace std;
class Base {
public:
int b;
int b1;
Base() : b(0), b1(0) { cout << "Base constructor" << endl; }
virtual void Input() {
cout << "Enter number b : ";
cin >> b >> b1;
// return *this;
}
virtual ~Base() {}
};
class Derived : public Base {
public:
int d;
// Constructor
Derived() : d(0) { cout << "Derived constructor" << endl; }
void Input() {
Base::Input();
cout << "Enter number d : ";
cin >> d; //>> d1;
// return *this;
}
~Derived() {}
};
int main() {
Base *s = new Derived[2];
// When complexity of data members increases this line causes
// segmentation fault
s[1].Input(); // Here the problem
delete[] s;
}