Access Specifiers and Virtual Functions

What are the accessibility rules when virtual functions are declared under three different access specifiers defined by C ++ (public, private, protected) What is the meaning of each of them? Any simple code examples to explain the concept will be very helpful.

+1
source share
2 answers

Access specifiers apply just like any other name when searching for a name. The fact that the function is virtual does not matter at all.

There is a common mistake that sometimes happens regarding virtual functions.

, , . , , . , " " .

// Brain compiled code ahead
struct A{
   virtual void f() {}
private:
   virtual void g() {}
protected:
   virtual void h() {}
};

struct B : A{
private:
   virtual void f() {}           // Allowed, but not a good habit I guess!
};

B b;
A &ra = b;

ra.f();    // name lookup of 'f' is done in 'A' and found to be public. Compilation 
           // succeeds and the call is dynamically bound
           // At run time the actual function to be called is 'B::f' which could be private, protected etc but that does not matter
+8

( ), .

:

. , .

Public - , / . , ( ) /.

, , :

class A : [public | protected | private] B
{
};

// infront of B . "" , , , , ( ).

, class A : public B , , class A : private B .

, . , !

0

Source: https://habr.com/ru/post/1683665/


All Articles