Home > OS >  Calling inherited functions and overriding behavior in c
Calling inherited functions and overriding behavior in c

Time:12-31

Why does this give this error - 'void D::func(const D &)': cannot convert argument 1 from 'const C' to 'const D &'

How to correct this, I want to call Base's func from Derived's func but note func is a friend function?

class C
{
public:
    C()
    {
        cout << "in C ctor" << endl;
    }

    friend void func(const C& abc1)
    {
        cout << "in C's func" << endl;
    }
};

class D : public C
{
public:
    D()
    {
        cout << "in D ctor" << endl;
    }

    void func(const D& abc)
    {
        func(static_cast<const C&>(abc));
        cout << "in D's func" << endl;
    }
};

int main()
{
    D d;
    d.func(d);
}

why does this similar e.g. work though -

https://ideone.com/eNmvng

CodePudding user response:

I'm not sure what that syntaxis does with function visibility, but this works:

class C
{
public:
    C()
    {
        cout << "in C ctor" << endl;
    }

    friend void func(const C& abc1);
};

void func(const C& abc1)
{
    cout << "in C's func" << endl;
}

class D : public C
{
public:
    D()
    {
        cout << "in D ctor" << endl;
    }

    void func(const D& abc)
    {
        ::func(abc);
        cout << "in D's func" << endl;
    }
};

int main()
{
    D d;
    d.func(d);
}

Just for completeness sake, this works too:

class C
{
public:
    C()
    {
        cout << "in C ctor" << endl;
    }

    friend void func(const C& abc1)
    {
        cout << "in C's func" << endl;
    }
};

// Make function visible in global scope
void func(const C& abc1);

class D : public C
{
public:
    D()
    {
        cout << "in D ctor" << endl;
    }

    void func(const D& abc)
    {
        ::func(abc);
        cout << "in D's func" << endl;
    }
};

int main()
{
    D d;
    d.func(d);
}
  • Related