Note that there are some explanatory texts on larger screens.

plurals
  1. POc++ using declaration, scope and access control
    primarykey
    data
    text
    <p>Typically the 'using' declaration is used to bring into scope some member functions of base classes that would otherwise be hidden. From that point of view it is only a mechanism for making accessible information more convenient to use.<br> However: the 'using' declaration can also be used to change access constraints (not only for functions but also for attributes). For example: </p> <pre><code>class C{ public: int a; void g(){ cout &lt;&lt; "C:g()\n"; } C() : a(0){} }; class D : public C{ private: using C::a; using C::g; public: D() { a = 1; } }; int main(void){ D d; cout &lt;&lt; d.a &lt;&lt; endl; //error: a is inaccessible C *cp = &amp;d; cout &lt;&lt; cp-&gt;a &lt;&lt; endl; //works d.g(); //error: g is inaccessible cp-&gt;g(); //works return 0; } </code></pre> <p>I think this limitation of access in the derived class is actually of no use, because you can always access g() and a from a pointer to the base class. So should't there be at least some kind of compiler warning? Or wouldn't it been even better to forbid such limitation of access by a derived class? The using declaration is not the only possibility to add constraints to access. It could also be done via overriding a base class' function an placing it in a section with more access constraints. Are there some reasonable examples where it is indeed nessecary to limit access in such a way? If not I don't see why it should be allowed. </p> <p>And another thing: at least with g++ the same code compiles well without the word 'using'. That means for the example above: it's possible to write C::a; and C::g; instead of using C::a; using C::g; Is the first only a shortcut for the latter or are there some subtle differences? </p> <p>//EDIT:<br> so from the discussion and answers below my conclusion would be:<br> - it's allowed to limit access constraints in derived classes with public inheritance<br> - there are useful examples where it could be used<br> - it's use might cause problem in combination with templates (e.g. a derived class could not be a valid parameter for some template class/function any more although it's base is)<br> - a cleaner language design should not allow such use<br> - compiler could at least issue some kind of warning</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload