C ++ - overriding or overloading functions

class A
{
     public:
          int func1()
          {
                cout<<"A func1";
          }
}

class B:public A
{
     public:
          int func1()
          {
                cout<<"B func1";
          }
}

in the code snippet above, is func1 () function overloaded in class B?

or get an override of class B ..?

+3
source share
3 answers

Overriding can happen only when the function of an element of the base class is declared virtual. Overloading can happen only when two functions have different signatures.

None of these conditions apply here. In this case, B::func1just hiding A::func1.

: I, , , . B::func1(int i), , B::func1 A::func1 - ++.

gory: b->func1(), ++ func1 B; B , , b->func1() B::func1(int i). A::func1() B::func1(int i), using A::func1 B, :

class B: public A
{
public:
    using A::func1;
    int func1(int i)
    {
        cout << "B func1(" << i << ")\n";
    }
};

, .

+13

func1 A virtual, B func1, , func1 A.

+3

In an inherited base class, if (for a simple understanding of the accepted public qualifier) ​​the public qualifier has a member function in the base class, and if we call the base class through the main function by creating an object of the base class, than the output of the base member function is a class, rather than a member function of the parent class, which means the function is overridden.

(provided that the name of the member function must be the same).

#include<iostream.h>

class a
{
    public:
    {
        cout<<"Hello from class a";
    }
};


class b:public a
{
    public:
    void hello()
    {
        cout<<"Hello from class b";
    }
};


main()
{
    b obj;
    obj.hello();
}

Output:

Hi from class b

-1
source

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


All Articles