-
using directive.
I ran across something curious in C++. I have always associated the using directive with namespaces, but this one I have not encountered until now.
I saw something like the following code in my work and have not found an explanation of why the code works as it does.
test.cpp:
Code:
#include <stdio.h>
class test1
{
protected:
virtual void afunct() =0;
};
class test2 : public test1
{
public:
void afunct(void);
};
class test3 : protected test2
{
public:
void bfunct(void);
using test2::afunct;
};
void test2::afunct(void)
{
printf("afunct()\n");
}
void test3::bfunct(void)
{
printf("bfunct()\n");
}
void main()
{
test2 v1;
test3 v2;
v1.afunct();
v2.bfunct();
v2.afunct();
}
I compile and run it and it works. Comment out the using directive and afunct() is not accessible through class test3. Part of my confusion may be due to the fact that I never really got the hang of protected.
I am just curious as to how/why it works the way it does.
-
Because test3 uses protected inheritence to inherit from test2, the afunct function is protected in test3 and, therefore, the main function cannot access it directly.
The using directive changes the access of the inherited function afunct to public, because it is under the public: label, allowing main to access it.
At least, I think that's how it works. :p
-
O.k., found it. C++ programmers guide, pg 407. It is as Ushakal says, the using directive makes the function publicly available.
Thanks..
-
By the way, that is a using declaration, not a using directive.