ProDeveloperTutorial.com

Tutorials and Programming Solutions
Menu
  • Shell Scripting
  • System Design
  • Linux System Programming
  • 4g LTE
  • Coding questions
  • C
  • C++
  • DSA
  • GIT
  • 450 DSA Cracker
  • 5G NR
  • O-RAN

C++ Chapter 20: Scope resolution operator in C++

prodevelopertutorial January 27, 2020

In this tutorial we shall see different uses of Scope Resolution Operator

  1. To access a global variable.
  2. In case of multiple inheritance.
  3. To Access class static variables.
  4. To access static member function
  5. To define a function outside the class.

 

1. To access a global variable.

 

#include <iostream>
using namespace std;

int num = 10;

int main(void)
{

    int num = 20;

    cout<<"Local num value "<<num<<endl;

    cout<<"Global num value "<<::num<<endl;
}

Output:

 

Local num value 20

Global num value 10

 

2. In case of multiple inheritance.

 

#include <iostream>
using namespace std;

class Base
{

public:
    int num;

    Base()
    {
        num = 10;
    }
};

class Derived : public Base
{
public:
    int num;

    Derived()
    {
        num = 20;
    }

    void display()
    {
        cout<<"The base class num is "<<Base::num<<endl;

        cout<<"The derived class num is "<<Derived::num<<endl;
    }
};


int main(void)
{

    Derived dObj;

    dObj.display();
}

Output:

 

The base class num is 10

The derived class num is 20

 

3. To Access class static variables.

 

#include <iostream>
using namespace std;

class Base
{

public:

    static int num;
};

int Base::num = 20;

int main(void)

{

    cout<<"The static value is "<<Base::num<<endl;

}

Output:

The static value is 20

 

4. To access static member function

 

#include <iostream>
using namespace std;

class Base
{

public:
    static void display()
    {
        cout<<"The display function"<<endl;
    }
};

int main(void)
{

    Base::display();

}

Output:

The display function

 

5. To define a function outside the class.

#include <iostream>
using namespace std;

class Base
{

public:

    void display();

};

void Base::display()
{
    cout<<"In display function"<<endl;
}

int main(void)
{

    Base obj;
    obj.display();

}

 

Output:

In display function

 

List Of Tutorials available in this website:

C Programming 20+ ChaptersC++ Programming 80+ Chapters
100+ Solved Coding QuestionsData Structures and Algorithms 85+ Chapters
System design 20+ ChaptersShell Scripting 12 Chapters
4g LTE 60+ ChaptersMost Frequently asked Coding questions
5G NR 50+ ChaptersLinux System Programming 20+ chapters
Share
Email
Tweet
Linkedin
Reddit
Stumble
Pinterest
Prev Article
Next Article

About The Author

prodevelopertutorial

Follow this blog to learn more about C, C++, Linux, Competitive Programming concepts, Data Structures.

ProDeveloperTutorial.com

Tutorials and Programming Solutions
Copyright © 2022 ProDeveloperTutorial.com