Can derived classes directly access all members (variables and functions) that they inherit from the base class? If not which ones can they not directly access and if they can't access them directly how should they access them
OOPs
In today's technology-driven world, computer programming skills are in high demand. The object-oriented programming (OOP) approach is very much useful while designing and maintaining software programs. Object-oriented programming (OOP) is a basic programming paradigm that almost every developer has used at some stage in their career.
Constructor
The easiest way to think of a constructor in object-oriented programming (OOP) languages is:
- Can derived classes directly access all members (variables and functions) that they inherit from the base class? If not which ones can they not directly access and if they can't access them directly how should they access them?
Derived classes can directly access all members (variables and functions) that they inherit from the base class.
The public and protected members (variables and functions) defined in the base class can directly be accessed from within any function inside the derived class or by creating the derived class object in the main() function.
For example, there are two variables, one is public and another is protected, declared in the base class and they can be directly accessed in derived class functions.
#include <iostream>
using namespace std;
class BaseClass
{
public:
int a; // allowed to access by any class
protected:
int b; // allowed to access by the base class, derived classes, and friends
};
class DerivedClass: public BaseClass //mode is public
{
public:
DerivedClass()
{
a = 1; // public base member is allowed to access from derived class
b = 2; // protected base members is allowed to access from derived class
}
void print()
{
cout<<"a = "<<a<<endl;
cout<<"b = "<<b;
}
};
int main()
{
//create derived class object
DerivedClass d;
//call function to display a and b
d.print();
return 0;
}
Output
Step by step
Solved in 2 steps with 1 images