0

simple code that is supposed to create B and D classes but I have problems when creating class D

#include <iostream> using namespace std; class B { public: B() { cout << "B()\n"; }; virtual ~B() { cout << "~B()\n"; }; void print() { cout << "B\n"; }; }; class D : public B { public: D() { cout << "D()\n"; }; ~D() { cout << "~D()\n"; }; void print() { cout << "D\n"; }; }; int main() { B* p0, * p1; p0 = new B; p0->print(); delete p0; p1 = new D;//couts "B()" and "D()" after that p1->print();//couts "B" delete p1;//couts "~D()" and "~B()" after that }

28th Jun 2021, 8:15 AM
Giorgi Kekelidze
Giorgi Kekelidze - avatar
3 Antworten
+ 1
The program seems to work fine, what is the problem you are facing here ?
28th Jun 2021, 8:20 AM
Arsenic
Arsenic - avatar
0
Instead of using constructor of class D it uses constructor of class B and only constructor of Class D after that,instead of using print of class D it uses Print of Class B, it uses destructor of class D and destructor of class B after that
28th Jun 2021, 8:29 AM
Giorgi Kekelidze
Giorgi Kekelidze - avatar
0
Giorgi Kekelidze that's because class D is inheriting class B, and before calling derived class constructor, default constructor of all of its base class would be called. And as for call to print() function of class B is considered, it's because it is being called with a pointer(p1) of type "B" and as print() is not virtual so there is no reason for compiler to dispatch this call dynamically and look at what exactly pointer p1 is actually pointing to. try making the function virtual to call print() of class D👇 https://code.sololearn.com/c3nbIx8YIPl8/?ref=app
28th Jun 2021, 10:07 AM
Arsenic
Arsenic - avatar