Scope resolution operator and array of objects in c++

 Scope Resolution Operator


1 To access a global variable when there is a local variable with same name:

#include<iostream>
using namespace std;

int x;

int main()
{
int x = 10; // Local x
cout << "Value of global x is " << ::x;
cout << "\nValue of local x is " << x;
return 0;
}


 To define a function outside a class.

#include <iostream>
using namespace std;

class A {
public:
    // Only declaration
    void fun();
};

void A::fun() { cout << "fun() called"; }

int main()
{
    A a;
    a.fun();
    return 0;
}


Array of objects

you can create an array of objects to store multiple instances of a class.
This is particularly useful when you want to manage multiple objects of the same type efficiently.

#include<iostream>
using namespace std;

class Employee
{
  int id;
  char name[30];
  public:
 
  void getdata();
 
  void putdata();
};

void Employee::getdata()
{
  cout << "Enter Id : ";
  cin >> id;
  cout << "Enter Name : ";
  cin >> name;
}

void Employee::putdata()
{
  cout << id << " ";
  cout << name << " ";
  cout << endl;
}

int main()
{
 
  Employee emp[30];
  int n, i;
  cout << "Enter Number of Employees - ";
  cin >> n;
 
  for(i = 0; i < n; i++) {
    emp[i].getdata();
  }
   
 
  cout << "Employee Data - " << endl;
 
  for(i = 0; i < n; i++) {
    emp[i].putdata();
  }
    return 0;
}

Comments

Popular posts from this blog

programs of oops in c++

Basic DSA programs in c++

C++ Exception Handling and file handling