开发者

C++ - function overriding or overloading

开发者 https://www.devze.com 2023-01-20 02:47 出处:网络
class A { public: int func1() { cout<<\"A\'s func1\"; } } class B:public A { public: int func1() { cout<<\"B\'s func1\";
class A
{
     public:
          int func1()
          {
                cout<<"A's func1";
          }
}

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

in the above code snippet , is the function ' func1()' getting overloaded in cl开发者_运维知识库ass B ?

or getting overrided by class B ..?


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

Neither of these conditions applies here. In this case, B::func1 is simply hiding A::func1.

Side note: the condition I indicated for overloading is necessary but not sufficient in this case. Even if you declared B::func1(int i), so that the signatures were different, B::func1 would still hide A::func1 because of C++'s name lookup rules.

The gory details: When you write b->func1(), C++ looks for the name func1 first in the scope of B; since B has that name in its scope, the compiler ends its search right there and then, and will not look any further, even though b->func1() ultimately fails to match the signature B::func1(int i). You can change this behaviour, and overload A::func1() and B::func1(int i) by adding using A::func1 to the definition of B, thus:

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

Also, don't forget the required semicolons at the end of each class definition.


If you had made func1 in class A virtual then class B would be overriding func1, since it is not virtual, you are hiding the func1 implementation in A.


In inherited base class, if (for easy understanding taken public specifier) public specifier has member function in the base class and if we call the base class through main function by making an object of base class than the output is of member function of base class and not of parent class member function that means function is overridden.

(provided that name of member function should be 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 is:

Hello from class b

0

精彩评论

暂无评论...
验证码 换一张
取 消