I'm trying to understand what is happening with pointers of classes. I made a base class called A and B class which inherits after A. I thought that pointer of Base class can point on any class which inherits after base. But I have a problem with memory here and I don't know why.
#include <iostream>
using namespace std;
class A{
public:
A(){}
int zmienna_klasy_A;
A(int x){
cout << "Konstruktor klasy A\n";
zmienna_klasy_A = x;
}
virtual ~A(){}
};
class B: public A{
public:
B(){}
int zmienna_klasy_A;
B(int x) : A(20){
cout << "Konstruktor klasy B\n";
zmienna_klasy_A = 10000;
wypisz();
}
~B(){}
};
int main(){
A *obiekt_bazowy;
B *obiekt_pochodny;
obiekt_bazowy = new B;
obiekt_bazowy = obiekt_pochodny; // here is problem
delete obiekt_bazowy;
}
Also, when I don't allocate memory for B but just write:
int main(){
A *obiekt_bazowy;
B *obiekt_pochodny;
obiekt_bazowy = obiekt_pochodny;
}
it is okay. What is happening here?