Access Specifiers in Inheritance
Inheritance access specifiers determine how members of the base class are treated in the derived class. These access specifiers do not affect the base class’s own access control, but they control the visibility of inherited members in the derived class. There are three types: public, protected, and private inheritance.
- Public Inheritance
In public inheritance, the public and protected members of the base class remain public and protected in the derived class. This type of inheritance models an “is-a” relationship and is the most commonly used form. It allows derived class objects to access the public members of the base class.
General Syntax:
class Base {
public:
void show();
};
class Derived : public Base {
// Inherits show() as public
};
Example:
class Animal {
public:
void sound() { cout << “Animal makes sound”; }
};
class Dog : public Animal {
public:
void bark() { cout << “Dog barks”; }
};
int main() {
Dog d;
d.sound(); // Accessible due to public inheritance
d.bark();
return 0;
}
- Protected Inheritance
In protected inheritance, the public and protected members of the base class become protected in the derived class. This means these members can be accessed by the derived class and its subclasses, but not by external objects.
General Syntax:
class Base {
public:
void show();
};
class Derived : protected Base {
// show() is protected here
};
Example:
class Vehicle {
public:
void start() { cout << “Vehicle started”; }
};
class Car : protected Vehicle {
public:
void begin() {
start(); // Accessible within the derived class
}
};
int main() {
Car c;
// c.start(); // Error: ‘start’ is protected
c.begin();
return 0;
}
- Private Inheritance
In private inheritance, the public and protected members of the base class become private in the derived class. They are not accessible by derived class objects or further subclasses. This type is used when you want to use base class features without exposing them as part of the derived class’s interface.
General Syntax:
class Base {
public:
void show();
};
class Derived : private Base {
// show() is private in Derived
};
Example:
class Printer {
public:
void print() { cout << “Printing…”; }
};
class LaserPrinter : private Printer {
public:
void startPrint() {
print(); // Valid: accessible within class
}
};
int main() {
LaserPrinter lp;
// lp.print(); // Error: print is private
lp.startPrint(); // Valid
return 0;
}