2

I have a Base class where there are 2 overloaded expanded() functions I am overloading one of them in Derived class and trying to call the other one inside it.

class Base
{
public:
    bool expanded()
    {
        return false;
    }

    void expanded(bool isit)
    {
    }
};

class Derived : public Base
{
public:
    void expanded(bool isit)
    {
        expanded();
    }
};

This fails with compilation error: 'Derived::expanded': function does not take 0 arguments

selbie
  • 91,215
  • 14
  • 97
  • 163
Mukund
  • 19
  • 3

3 Answers3

0

The new method i.e. the method in child class hides the scope of the old one. To call it, you need to be explicit with the scope:

class Derived : public Base
{
public:
    void expanded(bool isit)
    {
        Base::expanded();
    }
};

and if you want to maintain the same interface, you'll need to redefine in the derived class.

class Derived : public Base
{
public:
    void expanded(bool isit)
    {
        Base::expanded();
    }
    bool expanded() 
    {
      return Base::expanded();
    }

};
Sisir
  • 3,665
  • 4
  • 21
  • 30
robthebloke
  • 7,832
  • 6
  • 11
  • But if you define `expanded()` in `Derived`, you wouldn't need to use `Base::expanded` in `expanded(bool)`, right? – Tas Sep 10 '19 at 05:17
0

The followings will work:

Solution 1:

class Derived : public Base
{
public:
    void someOtherMethod(bool isit)
    {
        expanded();
    }
};

Solution 2:

class Derived : public Base
    {
    public:
        void expanded(bool isit)
        {
            // Will call child's expanded(bool) and will become recursive.
            expanded(false);
        }
    };

Solution 3:

class Derived : public Base
{
public:
    void expanded(bool isit)
    {
        Base::expanded();
    }
};

When you define a method same as parent method in your child class, then any time that method name is encountered in the child class, the compiler will search for the definition in the child class only. That is what is happening here. As the child class' expanded takes 1 argument, compiler is expecting a parameter to be passed.

Sisir
  • 3,665
  • 4
  • 21
  • 30
0

Similar question has already been answered in Overloads of inherited member functions

Adding to the previous answer. There is no overloading across scopes – derived class scopes are not an exception to this general rule. You can easily solve your error by declaring Baseclass like this

class Derived : public Base
{
public:
    using Base::expanded;
    void expanded(int isit)
    {
        expanded();
    }
};
Inian
  • 71,145
  • 9
  • 121
  • 139
Sagar Sakre
  • 2,298
  • 20
  • 31