Contents
Can protected methods be accessed?
Protected keyword in Java refers to one of its access modifiers. The methods or data members declared as protected can be accessed from: Within the same class. Subclasses of same packages.
Can a protected method be overridden as public?
Yes, the protected method of a superclass can be overridden by a subclass. If the superclass method is protected, the subclass overridden method can have protected or public (but not default or private) which means the subclass overridden method can not have a weaker access specifier.
Why does a class’s destructor sometimes have to be specified as virtual?
This might create memory leaks as the instance of the derived class would still remain in memory even after the pointer instance has been deleted/destroyed from memory. To avoid such potential memory leak issues, virtual destructors are used.
Can we inherit protected method?
Private Members in a Superclass A subclass does not inherit the private members of its parent class. However, if the superclass has public or protected methods for accessing its private fields, these can also be used by the subclass.
When to use a non virtual protected destructor?
If the class does not need to be polymorphic, but still needs to allow its interface to be inherited, use a non-virtual protected destructor. Such a class can never be destroyed through a pointer, avoiding silent leaks due to slicing. This technique especially applies to classes designed to be private base classes.
Can a protected destructor be used as a base class?
This kind of class should never be used polymorphically, and a protected destructor helps to document this requirement directly in the code. Finally, some classes may require that they are never used as a base class. In this case, the class can be marked final. A normal non-virtual public destructor is fine in this case.
When to declare a virtual destructor in C + +?
Care should be taken with the special member functions of such a class. A class designed to be used polymorphically at run-time (through a pointer to the base class) should declare the destructor virtual. This allows the derived parts of the object to be properly destroyed, even when the object is destroyed through a pointer to the base class.
Why do Inheritors need to maintain protected variables?
Protected variables generally have some intrinsic invariance associated with them (or else they’d be public). Inheritors then need to maintain those properties, which people can screw up or willfully violate.