0% found this document useful (0 votes)
6 views11 pages

CPP OOP Encapsulation Inheritance Rules

The document outlines rules and examples for encapsulation and inheritance in C++. It emphasizes keeping data members private, using getter/setter functions, validating data, and ensuring public behavior. Additionally, it covers inheritance syntax, initializer lists, virtual functions, and the importance of private members not being inherited.

Uploaded by

algorydhem
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views11 pages

CPP OOP Encapsulation Inheritance Rules

The document outlines rules and examples for encapsulation and inheritance in C++. It emphasizes keeping data members private, using getter/setter functions, validating data, and ensuring public behavior. Additionally, it covers inheritance syntax, initializer lists, virtual functions, and the importance of private members not being inherited.

Uploaded by

algorydhem
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

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";
• }

You might also like