1. Home
  2. Coding Hub
  3. Coding Notes
  4. Cpp
  5. Cpp M7 Encapsulation
45% OFFBLACK FRIDAY SALE
Sale ends in
03Days
06Hrs
23Mins
12Secs
Claim
  1. Home
  2. Coding Hub
  3. Coding Notes
  4. Cpp
  5. Cpp M7 Encapsulation

Limited time offer

45% OFF

BLACK FRIDAY SALE

Sale ends in

03Days
06Hrs
23Mins
12Secs
Claim
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Underrated CoderUnderrated Coder
Underrated CoderUnderrated Coder
Resources
  • Coding Hub
  • Roadmap
  • DSA Sheet
  • Coding Notes
  • Coding Quiz
  • Code Compiler
  • Coder AI
Interview Preparation
  • 1:1 Mentorship
  • Interview Q&A
Community
  • Blog
  • Coder Community
Help & Support
  • Contact Us
  • Troubleshooting
  • Report a Bug
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Outline
IntroductionEnvironment SetupSyntax & StructureOutput (cout)Comments
Variables & ConstantsData TypesType ModifiersInput (cin)Basic OperatorsLogical & BitwiseType Casting
If...ElseSwitch StatementTernary OperatorWhile & Do-While LoopsFor LoopBreak & Continue
ArraysMulti-Dimensional ArraysC-Style Stringsstd::stringStructsEnums
FunctionsParametersReturn ValuesPass by ReferenceDefault ArgumentsOverloadingInline FunctionsRecursion
Memory AddressesPointersDereferencingPointers & ArraysPointer ArithmeticDynamic MemoryReferences
OOP IntroClasses & ObjectsAccess ModifiersClass MethodsConstructorsDestructorsEncapsulation, Getters & Setters
InheritanceInheritance ConstructorsPolymorphismOperator OverloadingRuntime Poly (Virtual)Abstract ClassesFriend FunctionsThe 'this' Pointer
STL IntroSequence ContainersAssociative ContainersUnordered ContainersContainer AdaptersIteratorsAlgorithms
ExceptionsTry/CatchCatch Allstd::exceptionFile StreamsReading Files & EOF
Templates (Generics)Smart PointersLambdasPreprocessorNamespaces
C++

Encapsulation, Getters & Setters

Overview

Encapsulation is the defensive shield of OOP. By making all class data private, you physically prevent external developers (or yourself, a month from now) from making catastrophic errors, like setting a Player's health to -5000 or altering a secure bankBalance directly.

However, other parts of the program still need to interact with that data. To solve this securely, we use Getters and Setters (also known as Accessors and Mutators). These are perfectly controlled public functions that act as gatekeepers. They allow external code to request data (Get) or change data (Set), but strictly on YOUR terms, allowing you to run validation logic before applying any changes.

Syntax

cpp
#include <iostream>
#include <string>

class Employee {
private:
    // SHIELDED DATA
    double salary;

public:
    // CONSTRUCTOR
    Employee() : salary(50000) {}

    // GETTER: Allows read-only access
    double getSalary() {
        return salary;
    }

    // SETTER: Allows modification, but enforces strict validation!
    void setSalary(double newSalary) {
        if (newSalary < 0) {
            std::cout << "Error: Salary cannot be negative!\n";
        } else {
            salary = newSalary; // Only updates if valid!
        }
    }
};

int main() {
    Employee emp;
    
    // emp.salary = -999; // ERROR: Private!
    
    emp.setSalary(-999);  // Denied by validation!
    emp.setSalary(60000); // Accepted!
    
    std::cout << "Salary: $" << emp.getSalary() << "\n";
    
    return 0;
}

Common Pitfalls

  • Writing Setters that do no validation. If you write void setHP(int h) { hp = h; }, you have effectively made the variable public, defeating the entire purpose of Encapsulation. Setters should almost always include if statements verifying the incoming data.

Interview Questions

Why should you append the const keyword to the end of a Getter function (e.g., double getSalary() const { return salary; })?

Appending const to the end of a method mathematically guarantees to the compiler that this specific method will NEVER modify any internal class variables. It is purely read-only. This allows the compiler to optimize the code heavily and allows constant Objects to call the getter securely.

Real-World Example

Using 'const-correct' Getters and highly secure Setters in a production environment.

example
cpp
#include <iostream>
#include <string>

class User {
private:
    std::string password;
    
public:
    User(std::string pass) : password(pass) {}
    
    // The 'const' guarantees this function will not mutate the Object
    std::string getPassword() const {
        return "********"; // Hiding the actual data for security!
    }
    
    void updatePassword(std::string oldPass, std::string newPass) {
        if (oldPass == password && newPass.length() >= 8) {
            password = newPass;
            std::cout << "Password Updated.\n";
        } else {
            std::cout << "Update Failed. Invalid credentials.\n";
        }
    }
};

Check Your Knowledge

Test your understanding of Encapsulation, Getters & Setters with these quick questions.

Question 1

What is the primary architectural purpose of a Setter method?

Take C++ Quiz
Outline
IntroductionEnvironment SetupSyntax & StructureOutput (cout)Comments
Variables & ConstantsData TypesType ModifiersInput (cin)Basic OperatorsLogical & BitwiseType Casting
If...ElseSwitch StatementTernary OperatorWhile & Do-While LoopsFor LoopBreak & Continue
ArraysMulti-Dimensional ArraysC-Style Stringsstd::stringStructsEnums
FunctionsParametersReturn ValuesPass by ReferenceDefault ArgumentsOverloadingInline FunctionsRecursion
Memory AddressesPointersDereferencingPointers & ArraysPointer ArithmeticDynamic MemoryReferences
OOP IntroClasses & ObjectsAccess ModifiersClass MethodsConstructorsDestructorsEncapsulation, Getters & Setters
InheritanceInheritance ConstructorsPolymorphismOperator OverloadingRuntime Poly (Virtual)Abstract ClassesFriend FunctionsThe 'this' Pointer
STL IntroSequence ContainersAssociative ContainersUnordered ContainersContainer AdaptersIteratorsAlgorithms
ExceptionsTry/CatchCatch Allstd::exceptionFile StreamsReading Files & EOF
Templates (Generics)Smart PointersLambdasPreprocessorNamespaces
C++

Encapsulation, Getters & Setters

Overview

Encapsulation is the defensive shield of OOP. By making all class data private, you physically prevent external developers (or yourself, a month from now) from making catastrophic errors, like setting a Player's health to -5000 or altering a secure bankBalance directly.

However, other parts of the program still need to interact with that data. To solve this securely, we use Getters and Setters (also known as Accessors and Mutators). These are perfectly controlled public functions that act as gatekeepers. They allow external code to request data (Get) or change data (Set), but strictly on YOUR terms, allowing you to run validation logic before applying any changes.

Syntax

cpp
#include <iostream>
#include <string>

class Employee {
private:
    // SHIELDED DATA
    double salary;

public:
    // CONSTRUCTOR
    Employee() : salary(50000) {}

    // GETTER: Allows read-only access
    double getSalary() {
        return salary;
    }

    // SETTER: Allows modification, but enforces strict validation!
    void setSalary(double newSalary) {
        if (newSalary < 0) {
            std::cout << "Error: Salary cannot be negative!\n";
        } else {
            salary = newSalary; // Only updates if valid!
        }
    }
};

int main() {
    Employee emp;
    
    // emp.salary = -999; // ERROR: Private!
    
    emp.setSalary(-999);  // Denied by validation!
    emp.setSalary(60000); // Accepted!
    
    std::cout << "Salary: $" << emp.getSalary() << "\n";
    
    return 0;
}

Common Pitfalls

  • Writing Setters that do no validation. If you write void setHP(int h) { hp = h; }, you have effectively made the variable public, defeating the entire purpose of Encapsulation. Setters should almost always include if statements verifying the incoming data.

Interview Questions

Why should you append the const keyword to the end of a Getter function (e.g., double getSalary() const { return salary; })?

Appending const to the end of a method mathematically guarantees to the compiler that this specific method will NEVER modify any internal class variables. It is purely read-only. This allows the compiler to optimize the code heavily and allows constant Objects to call the getter securely.

Real-World Example

Using 'const-correct' Getters and highly secure Setters in a production environment.

example
cpp
#include <iostream>
#include <string>

class User {
private:
    std::string password;
    
public:
    User(std::string pass) : password(pass) {}
    
    // The 'const' guarantees this function will not mutate the Object
    std::string getPassword() const {
        return "********"; // Hiding the actual data for security!
    }
    
    void updatePassword(std::string oldPass, std::string newPass) {
        if (oldPass == password && newPass.length() >= 8) {
            password = newPass;
            std::cout << "Password Updated.\n";
        } else {
            std::cout << "Update Failed. Invalid credentials.\n";
        }
    }
};

Check Your Knowledge

Test your understanding of Encapsulation, Getters & Setters with these quick questions.

Question 1

What is the primary architectural purpose of a Setter method?

Take C++ Quiz

C++ coding notes for Indian students — 72 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in C++

  1. Introduction
  2. Environment Setup
  3. Syntax & Structure
  4. Output (cout)
  5. Comments
  6. Variables & Constants
  7. Data Types
  8. Type Modifiers
  9. Input (cin)
  10. Basic Operators
  11. Logical & Bitwise
  12. Type Casting
  13. If...Else
  14. Switch Statement
  15. Ternary Operator
  16. While & Do-While Loops
  17. For Loop
  18. Break & Continue
  19. Arrays
  20. Multi-Dimensional Arrays
  21. C-Style Strings
  22. std::string
  23. Structs
  24. Enums
  25. Functions
  26. Parameters
  27. Return Values
  28. Pass by Reference
  29. Default Arguments
  30. Overloading
  31. Inline Functions
  32. Recursion
  33. Memory Addresses
  34. Pointers
  35. Dereferencing
  36. Pointers & Arrays
  37. Pointer Arithmetic
  38. Dynamic Memory
  39. References
  40. OOP Intro
  41. Classes & Objects
  42. Access Modifiers
  43. Class Methods
  44. Constructors
  45. Destructors
  46. Encapsulation, Getters & Setters
  47. Inheritance
  48. Inheritance Constructors
  49. Polymorphism
  50. Operator Overloading
  51. Runtime Poly (Virtual)
  52. Abstract Classes
  53. Friend Functions
  54. The 'this' Pointer
  55. STL Intro
  56. Sequence Containers
  57. Associative Containers
  58. Unordered Containers
  59. Container Adapters
  60. Iterators
  61. Algorithms
  62. Exceptions
  63. Try/Catch
  64. Catch All
  65. std::exception
  66. File Streams
  67. Reading Files & EOF
  68. Templates (Generics)
  69. Smart Pointers
  70. Lambdas
  71. Preprocessor
  72. Namespaces

Study next

  • All coding notes
  • C++ notes home
  • C++ certification quiz
  • Online compiler
  • Interview Q&A

C++ coding notes for Indian students — 72 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in C++

  1. Introduction
  2. Environment Setup
  3. Syntax & Structure
  4. Output (cout)
  5. Comments
  6. Variables & Constants
  7. Data Types
  8. Type Modifiers
  9. Input (cin)
  10. Basic Operators
  11. Logical & Bitwise
  12. Type Casting
  13. If...Else
  14. Switch Statement
  15. Ternary Operator
  16. While & Do-While Loops
  17. For Loop
  18. Break & Continue
  19. Arrays
  20. Multi-Dimensional Arrays
  21. C-Style Strings
  22. std::string
  23. Structs
  24. Enums
  25. Functions
  26. Parameters
  27. Return Values
  28. Pass by Reference
  29. Default Arguments
  30. Overloading
  31. Inline Functions
  32. Recursion
  33. Memory Addresses
  34. Pointers
  35. Dereferencing
  36. Pointers & Arrays
  37. Pointer Arithmetic
  38. Dynamic Memory
  39. References
  40. OOP Intro
  41. Classes & Objects
  42. Access Modifiers
  43. Class Methods
  44. Constructors
  45. Destructors
  46. Encapsulation, Getters & Setters
  47. Inheritance
  48. Inheritance Constructors
  49. Polymorphism
  50. Operator Overloading
  51. Runtime Poly (Virtual)
  52. Abstract Classes
  53. Friend Functions
  54. The 'this' Pointer
  55. STL Intro
  56. Sequence Containers
  57. Associative Containers
  58. Unordered Containers
  59. Container Adapters
  60. Iterators
  61. Algorithms
  62. Exceptions
  63. Try/Catch
  64. Catch All
  65. std::exception
  66. File Streams
  67. Reading Files & EOF
  68. Templates (Generics)
  69. Smart Pointers
  70. Lambdas
  71. Preprocessor
  72. Namespaces

Study next

  • All coding notes
  • C++ notes home
  • C++ certification quiz
  • Online compiler
  • Interview Q&A