Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the 'private' access modifier give the compiler more room for optimization?

Tags:

c++

oop

private

Does it allow the compiler to inline it, knowing that only functions in the same class can access it? Or is it only for the programmer's convenience?

like image 271
slartibartfast Avatar asked Sep 17 '11 17:09

slartibartfast


2 Answers

The compiler can (but is not required to) optimize as you suggest, but that's not the point. The point of access modifiers is to catch certain classes (no pun intended) of programming errors at compile time. Private functions are functions that, if someone called them from outside the class, that would be a bug, and you want to know about it as early as possible.

(Any time you ask the question "could the compiler make optimizations based on this information available to it", the answer is "yes, unless there's a specific rule in the standard that says it's not allowed to" (such as the rules for volatile, whose entire purpose is to inhibit optimizations). However, compilers do not necessarily bother optimizing based on any given piece of information. There is, after all, no requirement for compilers to do any optimization in the first place! How clever your compiler is, nowadays, largely depends on how long you are willing to let it run; MSVC's whole-program PGO mode is capable of inlining through virtual method dispatch -- it guesses the most likely target, and falls back to a regular virtual call at runtime if the guess was wrong -- but slows down compiles by at least a factor of two.)

like image 146
zwol Avatar answered Oct 19 '22 06:10

zwol


The access specifiers are a part of C++ mechanism to implement OOP principles of Encapsulation and Abstraction and not optimization for compilers.

Some intelligent compiler can possibly implement some optimization through it but it not enforced to do so by the C++ Standard. The purpose of access specifiers is not Optimization but to facilitate language constructs for principles supported by the C++ language.

like image 45
Alok Save Avatar answered Oct 19 '22 07:10

Alok Save