Virtual functions in C ++

In my C ++ program:

#include<iostream.h>

class A
{
    public:
    virtual void func()
    {
         cout<<"In A"<<endl;
    }
};

class B:public A
{
    public:
    void func()
    {
        cout<<"In B"<<endl;
    }
};

class C:public B
{
    public:
    void func()
    { 
        cout<<"In C"<<endl;
    }
};  

int main()
{
    B *ptr=new C;
    ptr->func();
}

operator must call B::func(). However, the function is called C::func(). Please shed some light on this. After deleting the virtual keyword in class "A" this does not happen anymore.

+3
source share
5 answers

For the basics, you should read the C ++ FAQ Lite for virtual functions .

, . , , , , , , . , .

+3

( , ). func() A, B C.

+7

B:: func()

C, C.

, , , , , , , .

+1

. , ptr C, , , B ( B *ptr, , C, C *ptr).

, B, , , , . C ( , , , func() ), .

, , , B- .

+1

:

B *obj = new B;

Then he would call B :: func ().
To appreciate the functionality you expect, you should remove the new func implementation in C.
If you use a virtual function, you actually say that I don’t know what type of object I have inside if it is from the same family of objects (in this A is the "father" of the "family"). All you know is that each member of the "family" must do other work for a specific part. For example:

class Father
{
public:
  virtual void func() { cout << "I do stuff"; }
};
class Child : public Father
{
public:
  virtual void func() { cout << "I need to do something completely different"; }
};

int main()
{
  Father *f = new Father;
  f->func(); // output: I do stuff
  delete f;
  f = new Child;
  f->func(); // output: I need to do something completely different
  delete f;
}
0
source

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


All Articles