How to call a parent class function from derived class function?

后端 未结 7 1098
自闭症患者
自闭症患者 2020-11-22 06:16

How do I call the parent function from a derived class using C++? For example, I have a class called parent, and a class called child which is deri

相关标签:
7条回答
  • 2020-11-22 07:15

    If access modifier of base class member function is protected OR public, you can do call member function of base class from derived class. Call to the base class non-virtual and virtual member function from derived member function can be made. Please refer the program.

    #include<iostream>
    using namespace std;
    
    class Parent
    {
      protected:
        virtual void fun(int i)
        {
          cout<<"Parent::fun functionality write here"<<endl;
        }
        void fun1(int i)
        {
          cout<<"Parent::fun1 functionality write here"<<endl;
        }
        void fun2()
        {
    
          cout<<"Parent::fun3 functionality write here"<<endl;
        }
    
    };
    
    class Child:public Parent
    {
      public:
        virtual void fun(int i)
        {
          cout<<"Child::fun partial functionality write here"<<endl;
          Parent::fun(++i);
          Parent::fun2();
        }
        void fun1(int i)
        {
          cout<<"Child::fun1 partial functionality write here"<<endl;
          Parent::fun1(++i);
        }
    
    };
    int main()
    {
       Child d1;
       d1.fun(1);
       d1.fun1(2);
       return 0;
    }
    

    Output:

    $ g++ base_function_call_from_derived.cpp
    $ ./a.out 
    Child::fun partial functionality write here
    Parent::fun functionality write here
    Parent::fun3 functionality write here
    Child::fun1 partial functionality write here
    Parent::fun1 functionality write here
    
    0 讨论(0)
提交回复
热议问题