C++: Declaring an object instance after a class scope

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

In C++, a class instance can be declared right after the class scope.  You might have notice that this method was used in the previous example.

As shown in the example below, music, rock and and rock1 instance variable were declared right after the class scope.

#include <iostream>

using namespace std;

class Music {
public:

    void setTop10(int i) {
        prot_Top10 = i;
    }

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

protected:

    int prot_Top10;

    void Protband() {

        prot_Top10 = 8;
        cout << "No of Top 10: " << prot_Top10 << endl << endl;
    }

} music;

class Rock : public Music {
public:

    void useProtBand() {
        Protband();
    }

} rock, rock1;

int main() {

    music.setTop10(2); 
    music.Display(); 

    rock.setTop10(5); 
    rock.Display(); 

    rock.useProtBand(); 

    rock1.setTop10(6);
    rock1.Display();

}

classinstance

Series Navigation<< C++: Protected members and functions
C++: Pointers in class >>

Leave a comment

Leave a Reply