Understanding virtual methods of C ++ virtual methods allocated on the stack

For the following code:

#include<iostream>
using namespace std;

class A{
public:
virtual int f(){return 1;}
};
class B : public A{
public:
virtual int f(){return 2;}
};
int main(int argc,char*argv[]){
    A b=B();
    cout<<b.f()<<endl;
}

I expect a number to be printed 2. Instead, the program prints the number 1.

Can someone explain why this is?

+3
source share
7 answers

What you did is called slicing. See What is cropping objects?

Instead, use pointers:

A* b = new B();
+9
source

This is due to slicing . Run-time polymorphism only works with a pointer or reference in C ++. You can get a virtual dispatch with another variable:

B b;
A& a = b;
cout << a.f() << endl;

Or you can directly assign a pointer, for example here:

A* aptr = new B;
aptr->f();
delete aptr;

B . , . GCC -Wnon-virtual-dtor .

+6

, A, B. :

A a = B(); 

B, A A, A.

, :

int main() {
   B b;
   A &a = b;  // an A reference to the B object
   A *p = &b; // an A pointer to a B object
   a.f();     // will dispatch to B::f
   p->f();    // will dispacth to B::f
}
+6

, . "b" - "A". A:

A::A(const A& other);

, "B" "A"; "A". "A" , , .

, , .

+1

, ++. :

int main(int argc,char*argv[]){
    B b;
    A* a=&b;
    cout<<a->f()<<endl;
}
0

, , . , b ( A) , A, , B() .

0
#include<iostream> 
using namespace std;  
class A
{ 
    public: virtual int f()
    {
       return 1;
    } 
};

class B : public A
{ 
public:
    virtual int f()
    {
       return 2;
    } 
};
int main(int argc,char*argv[])
{     
      A * b = new B();
      cout << b->f() << endl;
      delete b;
} 
0
source

Source: https://habr.com/ru/post/1786007/


All Articles