Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using declaration (Derived class)

struct B1{
  int d;
  void fb(){};
};

struct B2 : B1{
  using B1::d;
  using B1::fb;

  int d;               // why this gives error?
  void fb(){}          // and this does not?
};

int main(){}

Is it because, B1::fb() is treated as B1::fb(B1*) and B2::fb() treated as B2::fb(B2*)? That is, does the implicit parameter, help in distinguishing these?

$13.3.1/4-

For nonconversion functions introduced by a using-declaration into a derived class, the function is considered to be a member of the derived class for the purpose of defining the type of the implicit object parameter.

like image 416
Chubsdad Avatar asked Aug 23 '10 04:08

Chubsdad


People also ask

How do you declare a derived class?

In the declaration of a derived class, you list the base classes of the derived class. The derived class inherits its members from these base classes. The qualified_class_specifier must be a class that has been previously declared in a class declaration. An access specifier is one of public , private , or protected .

What is the use of using declaration in C++?

A using declaration in a definition of a class A allows you to introduce a name of a data member or member function from a base class of A into the scope of A .

What is the use of using declaration?

A using declaration introduces an unqualified name as a synonym for an entity declared elsewhere. It allows a single name from a specific namespace to be used without explicit qualification in the declaration region in which it appears.

What is the use of derived class?

Derived Class: A class that is created from an existing class. The derived class inherits all members and member functions of a base class. The derived class can have more functionality with respect to the Base class and can easily access the Base class. A Derived class is also called a child class or subclass.


1 Answers

The C++ standard (C++03 §7.3.3/12) explains:

When a using-declaration brings names from a base class into a derived class scope, member functions in the derived class override and/or hide member functions with the same name and parameter types in a base class (rather than conflicting).

In your example, B2::fb() hides the B1::fb() introduced by the using declaration.

As for why it is ill-formed to have both using B1::d; and int d; in the definition of B2, the C++ standard (C++03 §7.3.3/10) explains:

Since a using-declaration is a declaration, the restrictions on declarations of the same name in the same declarative region also apply to using-declarations.

So, it is ill-formed for the same reason that the following is ill-formed: it results in two objects with the same name in a single declarative region:

struct S { int d; int d; };
like image 159
James McNellis Avatar answered Oct 20 '22 09:10

James McNellis