user16188058
user16188058

Reputation:

About virtual functions

I have the following code snippet:

#include <iostream>
#include <typeinfo>
using namespace std;

class A{
public:
    int x;
    A(int i = 0): x(i) {}
    A minus(){
        return 1 - x;
    }
    virtual void print(){
        cout << x << "\n";
        cout << "Base print\n";
    }
};

class B: public A{
    int y;
public:
    B(int i = 0) {x = i;}
    void print(){
    cout << x << "\n";
    cout << "Derived print!\n";
    }
   };

int main(){
    A* p1 = new B(18);
    *p1 = p1->minus();
    p1->print();

    return 0;
}

The output is:

-17
Derived print!

I know where -17 comes from. It does upcasting and A* p1 = new B(18) and makes p1 point to a derived object with x value of 18. *p1 = p1->minus make the object that p1 points to be an A(-17) /// cause 1 -18 = -17. My question is, where does the second line come from ? If p1 points to an A object after the *p1 = p1->minus(), why does p1->print() not print "Base print" ?

Upvotes: 0

Views: 88

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 310910

You created an object of the type class B

A* p1 = new B(18);

So the pointer p1 will point to this object until it (the pointer) will be reassigned.

In this statement

*p1 = p1->minus();

the dynamically created object of the type class B was not deleted. Only its sub-object of the type class A was changed using the implicitly defined by the compiler copy assignment operator of the class A and the pointer p1 still points to the same object of the type class B.

Thus in this statement

p1->print();

there is called the virtual function of the object of the type class B that by the way should be declared in the class B at least like

void print() override
{
    //..
}

Pay attention to that you should declare a virtual destructor in the class A. For example

virtual ~A() = default;

And before exiting main you should delete the dynamically allocated object.

delete p1;

Upvotes: 4

Related Questions