PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, October 26, 2022

[FIXED] Why the parent's method should be called explicitly with the parent's prefix from the child object?

 October 26, 2022     c++, class, hierarchy, oop     No comments   

Issue

see please the code:

#include <iostream>

using namespace std;


class A{
public:
    A() = default;
    
    virtual void foo() = 0;
    
    bool foo(int x)
    {
        cout<<"A::foo(int x)\n";
        return true;
    }
    
     bool func(int x)
    {
        cout<<"A::func(int x)\n";
        return true;
    }
    
};

class B: public A
{
    
    public:
    B() = default;
    
    void foo()
    {
         cout<<"B::foo()\n";
    }
    
};

int main()
{
    B b;

    b.func(0);
    
    //b.foo(0); //it's not compiled
    b.A::foo(0);
    
    return 0;
}

It seems the parent's method should be called explicitly with the parent's prefix from the child object for any reason. b.foo(0) is not compiled but if I add A:: prefix like b.A::foo(0) it works. Why is b.foo(0) not compiled but b.func(0) is?


Solution

It is called 'name hiding'.

You have a function called foo without parameters in your subclass. The compiler will hide any other function with the same name from the superclass, unless you declare it with the using A::foo; directive in the child class.

To my knowledge, this is done to avoid confusion of the function calls. All non-overloaded functions will be inherited automatically.

Your code should work, if you write it like this (untested):

class B: public A
{
    
    public:
    using A::foo;
    B() = default;
    
    void foo()
    {
         cout<<"B::foo()\n";
    }
    
};

Please note that the using syntax will move ALL functions called foo into your subclass, regardless of their prototype.

For further information, see https://www.ibm.com/docs/en/zos/2.3.0?topic=scope-name-hiding-c-only or https://bastian.rieck.me/blog/posts/2016/name_hiding_cxx/



Answered By - Refugnic Eternium
Answer Checked By - David Goodson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing