简体   繁体   中英

Virtual functions c++

I have tried to do some exercises and when I finally think I understood, it came an exercise who ruins everything. For example I have the following classes:

class A
{
public:
    A() {std::cout<<"A()";}
    virtual ~A(){std::cout<<"~A()";} 

    virtual void print() {std::cout<<"A";}
};

class B : public A
{
public:
    B() {std::cout<<"B()";}
    virtual ~B(){std::cout<<"~B()";} 

    virtual void print() {std::cout<<"B";}
};

And the following code snippets:

void f3()
{
    A a[2];
    a[1]=B();
    a[1].print();
}

And the result I think its:

A() A()
A() B() {not sure why there is an A() too)
A - and here I really don't know because either A and B are virtual(and I have in the notebook A) 
~B() ~A()
~A() ~A()

And another code snippets:

void f4()
{
    A* a[]={new A(), new B()};
    a[0]->print();
    a[1]->print();
    delete a[0];
    delete a[1];
}

And here is a problem too. We have

A() {here I don t know why there is an A()}
A() B()
A
B
~B() ~A()
A()

But it's correct? And why here we have A and B and not B and A?I mean, in the first exercise I have A when it was type of B() and here it's how I think it's normal but why?

A() A()

You created an array of two A's, so two calls of A ctor.

A() B() {not sure why there is an A() too)

You created a B ( B() ), and Bs are derivated from As, so the steps are: allocation of memory to store a B, call of A's ctor for the A-part, call of B's ctor for the B-part.

A - and here I really don't know because either A and B are virtual(and I have in the notebook A)

You assigned the fresh created B to an A, so this cause the copy of the A-part of the B to the destination A. Then you called print on the A, and this prints A .

~B() ~A()
~A() ~A()

dtors are called in the exact reverse of ctors.

In your second try, you use pointers and dynamic allocations, and in this case polymorphism is used. Your array is an array of two pointers to type A, initialized with (the address of) two objects: the first begin an A, the second a B.

When you call a[0]->print() , a[0] is an address of an A, so the method print of it is called.

When you call a[1]->print() , a[1] is an address of a B, so the method print of it is called, because print is virtual .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM