D
developer.new
Hi
I have a question regarding this concept I learned about recently:
Name Hiding. Here's what I've come across:
There is a base class with two functions with the same name but
different signature. A class inherits publicly from this base class
and redefines one of the two functions in the derived class. In that
case, a derived class object cannot access the other base class
function that it hasn't redefined. I'm posting a code snippet to make
it clear.
class Base {
public:
int f () { cout << "Base::f_int" << endl; return 1; }
int f (string s_) { cout << "Base::f_str" << endl; return 1; }
};
class Derived : public Base {
public:
int f() { cout << "Derived::f_int" << endl; return 1;}
};
int main() {
string str_ = "blahhh";
Derived d1;
d1.f();
d1.f(str_); //Gives compilation error!!!!!!
d1.Base::f(str_); //This of course, works.
return 0;
}
Going by how C++ uses name mangling to create unique function names, I
thought it would be possible to access the Base class "int f (string)"
function directly from the derived object.
Any idea why this cannot be done? I know it's a not a good practice to
have functions with duplicate names and all that. But my question is
more about inheritance. Why does this function become inaccessible
from the derived class?
Would really appreciate answers
- ND
I have a question regarding this concept I learned about recently:
Name Hiding. Here's what I've come across:
There is a base class with two functions with the same name but
different signature. A class inherits publicly from this base class
and redefines one of the two functions in the derived class. In that
case, a derived class object cannot access the other base class
function that it hasn't redefined. I'm posting a code snippet to make
it clear.
class Base {
public:
int f () { cout << "Base::f_int" << endl; return 1; }
int f (string s_) { cout << "Base::f_str" << endl; return 1; }
};
class Derived : public Base {
public:
int f() { cout << "Derived::f_int" << endl; return 1;}
};
int main() {
string str_ = "blahhh";
Derived d1;
d1.f();
d1.f(str_); //Gives compilation error!!!!!!
d1.Base::f(str_); //This of course, works.
return 0;
}
Going by how C++ uses name mangling to create unique function names, I
thought it would be possible to access the Base class "int f (string)"
function directly from the derived object.
Any idea why this cannot be done? I know it's a not a good practice to
have functions with duplicate names and all that. But my question is
more about inheritance. Why does this function become inaccessible
from the derived class?
Would really appreciate answers
- ND