This blog is about providing theory as well as simple executable codes of different programming languages such as java, C, C++, and web programming, etc. This blog will be helpful to the IT students to learn about programming.

Tuesday, February 28, 2023

What are the different types of visibility modes used in Inheritance? Discuss.

 In C++, visibility modes are used to determine the access of the derived class to the members of the base class. There are three visibility modes used in inheritance, which are as follows:

1. Public Inheritance: In public inheritance, all the public members of the base class become public members of the derived class, and all the protected members of the base class become protected members of the derived class. Private members of the base class are not accessible in the derived class.

Example:

class Base {
public:
    int public_member;
protected:
    int protected_member;
private:
    int private_member;
};
class Derived : public Base {
public:
    void access_base_members() {
        public_member = 1; // Accessible
        protected_member = 2; // Accessible
        // private_member = 3; Not accessible
    }
};

2. Protected Inheritance: In protected inheritance, all the public and protected members of the base class become protected members of the derived class. Private members of the base class are not accessible in the derived class.

Example:

class Base {
public:
    int public_member;
protected:
    int protected_member;
private:
    int private_member;
};
class Derived : protected Base {
public:
    void access_base_members() {
        public_member = 1; // Accessible
        protected_member = 2; // Accessible
        // private_member = 3; Not accessible
    }
};

3. Private Inheritance: In private inheritance, all the public and protected members of the base class become private members of the derived class. Private members of the base class are not accessible in the derived class.

Example:

class Base {
public:
    int public_member;
protected:
    int protected_member;
private:
    int private_member;
};
class Derived : private Base {
public:
    void access_base_members() {
        public_member = 1; // Accessible
        protected_member = 2; // Accessible
        // private_member = 3; Not accessible
    }
};

These visibility modes are used to implement various access control policies in object-oriented programming. The choice of visibility mode depends on the design of the system and the requirements of the application.

No comments:

Post a Comment

If you have any doubts, please let me know

Slider Widget