Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access specifiers and virtual functions

Tags:

c++

virtual

What are the rules for accessibility when virtual functions are declared under 3 different access specifiers specified by C++(public, private, protected) What is the significance of each? Any simple code examples to explain the concept will be highly useful.

like image 439
Alok Save Avatar asked Jan 25 '26 13:01

Alok Save


1 Answers

Access specifiers apply in the same way as they would to any other name during name lookup. The fact that the function is virtual does not matter at all.

There is a common mistake which sometimes happens with respect to virtual functions.

If name lookup determines a viable function to be a virtual function, the access specifier of the virtual function is checked in the scope of the static type of the object expression used to name the function. At run time, the actual function to be called could be defined in the derived class with a completely different access specifier. This is because 'access specifiers' are a compile time phenomonon.

// 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
like image 92
Chubsdad Avatar answered Jan 27 '26 03:01

Chubsdad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!