Lecture 6 Class Hierarchies
Lecture 6 Class Hierarchies
int main() {
Sub object;
object.put(100);
object.put(object.get() + 1);
cout << object.get() << endl;
}
• This code defines a class named Sub that inherits from a class named Super.
• The Sub class doesn't introduce any new variables or functions.
OOP, Muhammad Ehsan
Private Inheritance by Default
• Compilation Errors
• Compiling the previous code without a visibility specifier results in
errors.
• Why? Private inheritance is assumed by default.
class Super {
int main() {
protected:
Sub object;
int storage;
public:
object.put(100);
void put(int val) {
object.put(object.get() + 1);
storage = val;
object.print();
}
}
int get() {
}
from Super, can access the storage
}; variable through its member functions.
OOP, Muhammad Ehsan
Protected vs Private Members
• Protected members: Accessible within the subclass hierarchy
• Private members: Only accessible within the class itself
storage = val; };
}
int main() {
int get() {
Sub object;
return storage;
}
object.put(1);
};
object.insert(2);
class SuperB {
object.put(object.get() + object.takeout());
protected:
object.insert(object.get() + object.takeout());
int safe;
object.print();
public:
}
void insert(int val) {
safe = val;
} storage = 3
OOP, Muhammad Ehsan
}; safe = 5