Wednesday, December 3, 2014

constructor & Scope resolution operator in c++



C++ constructor example

#include 
#include  
class Game 
{
 private:
 
int goals;
 
public:
  Game() 
{
    goals = 0;
  }
 
 
  int getGoals()
 {
    return goals;
  }
  void incrementGoal()
{
    goals++;
  }
};
 
int main()
 {
  Game football;
 
  cout << "Number of goals when game is started = " << football.getGoals() << endl;
 
  football.incrementGoal();
  football.incrementGoal();
 
  cout << "Number of goals a little later = " << football.getGoals() << endl;
 
  return 0;
}

C++ new operator example

#include 
 #include  
int main()
{
   int n, *pointer, c;
 
   cout << "Enter an integer\n";
   cin >> n;
 
   pointer = new int[n];
 
   cout << "Enter " << n << " integers\n";
 
   for ( c = 0 ; c < n ; c++ )
      cin >> pointer[c];
 
   cout << "Elements entered by you are\n";
 
   for ( c = 0 ; c < n ; c++ )
      cout << pointer[c] << endl;
 
   delete[] pointer;
 
   return 0;
}

Scope resolution operator in c++

#include 
#include  
class programming 
{
public:
  void output();  
};
 
void programming::output() 
{
  cout << "Function defined outside the class.\n";
}
 
int main() 
{
  programming x;
  x.output();
 
  return 0;
}

No comments:

Post a Comment