On name lookup in C++ inheritance

  • 2020-05-12 02:55:20
  • OfStack

Examples are as follows:


#include<iostream>
#include<string>
using namespace std;
class Base {
 public:
 void func() {
  cout << "func() in Base." << endl;
 }
 void func(int a) {
  cout << "func(int a) in Base." << endl;
 }
 void func(string s) {
  cout << "func(string s) in Base." << endl;
 }
};


class Derived : public Base { 
public:
 //using Base::func;
 void print() {
  cout << "func() in Derived." << endl;
 }
};


int main() {
 Derived d;
 d.Base::func();// Specify the base class version 
 d.func();
 d.func(12);//error, Can be added in a derived class using Base::print;
 d.func("abc");//error Can be added to a derived class using Base::print;
 system("pause");
 return 0;
}
//1 The static types of objects, references, and Pointers determine which members of the object are visible. 
// The derived class scope is nested within the base class scope 
// Derived class members mask base class members with the same name 
// If the derived class wants to use an overloaded version of a base class by its own type , The derived class must either override all overloaded versions , either 1 Not one of them. 
// using using The declaration adds all overloaded versions of the base class to the derived class scope 
// The name lookup precedes type checking, and if the name of the function is found in the derived class, the lookup does not proceed up, followed by type checking 

Related articles: