C++ OOP: Encapsulation &
Inheritance Rules with Examples
Rules and Code Examples
Rule 1: Keep data members private
• class Student {
• private:
• int age; // can't be accessed directly from
outside
• };
Rule 2: Use get/set functions
• class Student {
• private:
• int age;
• public:
• void setAge(int a) { age = a; }
• int getAge() { return age; }
• };
Rule 3: Validate data in setters
• void setAge(int a) {
• if (a > 0) age = a;
• else age = 1;
• }
Rule 4: Keep behavior (methods)
public
• public:
• void display() {
• cout << "Age: " << age;
• }
Rule 1: Use ':' to inherit from base
class
• class Person {
• public:
• void speak() { cout << "Speaking\n"; }
• };
• class Student : public Person {};
Rule 2: Use initializer list
• class Person {
• public:
• Person(string n) { cout << "Hello " << n <<
endl; }
• };
• class Student : public Person {
• public:
• Student(string name) : Person(name) {}
Rule 3: Use virtual for override
• class Person {
• public:
• virtual void speak() { cout << "Person
speaking\n"; }
• };
• class Student : public Person {
• public:
• void speak() override { cout << "Student
speaking\n"; }
Rule 4: Virtual destructor in base
• class Person {
• public:
• virtual ~Person() {
• cout << "Base destructor\n";
• }
• };
Rule 5: Private members are not
inherited
• class Person {
• private:
• int age;
• };
• class Student : public Person {
• void show() {
• // cout << age; ❌ Not allowed
• }
Rule 6: Use override keyword
• void speak() override {
• cout << "Overridden correctly\n";
• }