C++: Protected members and functions

This entry is part 53 of 61 in the series C++

As mentioned, protected data members and functions can only be accessed by the class that  declared these functions.

Consider the following example for protected prot_Top10 and function Protband.  An error will be generated if you try to acess it in main as they are not public.

#include <iostream>

using namespace std;

class Music {

    void setTop10(int i) {
        prot_Top10 = i;

    void Display() {
        cout << "No of Top 10: " << prot_Top10 << endl;


    int prot_Top10;

    void Protband() {

        prot_Top10 = 8;  //Ok, accessed by its own class
        cout << "Access allowed by derived class member functions, no of Top 10: " << prot_Top10 << endl << endl;

} music;

class Rock : public Music {

    void useProtBand() {

} rock, rock1;

int main() {

    music.setTop10(2); // OK, uses public access function
    music.Display(); //Ok, Display is public

    rock.setTop10(5); // OK, uses public access function
    rock.Display(); //Ok, Display is public

    // music.Protband();         error, Protband() is protected.  The main could not access it unless it is public.  Only member functions of its class can acess it

    rock.useProtBand(); // OK, uses public access function in derived class




Series Navigation<< C++: Assessing class members from main
C++: Declaring an object instance after a class scope >>