News:

MyKidsDiary.in :: Capture your kids magical moment and create your Online Private Diary for your kids

Main Menu

C++ [Complete Function Arguments ]

Started by dhilipkumar, Dec 15, 2008, 06:28 PM

Previous topic - Next topic

dhilipkumar

A example of default arguments.

#include <iostream>
using namespace std;

void f(int a=0, int b=0)
{
  cout << "a: " << a << ", b: " << b;
  cout << '\n';
}

int main()
{
  f();
  f(10);
  f(10, 99);

  return 0;
}

Compute area of a rectangle using default arguments.


#include <iostream>
using namespace std;


double rect_area(double length, double width = 0)
{
  if(!width)
     width = length;
  return length * width;
}

int main()
{
  cout  << "10 x 5.8 rectangle has area: ";
  cout << rect_area(10.0, 5.8 ) << '\n';

  cout  << "10 x 10 square has area: ";
  cout << rect_area(10.0) << '\n';

  return 0;
}

Use default argument


#include <iostream>
using namespace std;

class myclass {
  int x;
public:

  myclass(int n = 0) {
     x = n;
  }
  int getx() {
     return x;
  }
};

int main()
{
  myclass o1(10);          // declare with initial value
  myclass o2;              // declare without initializer

  cout << "o1: " << o1.getx() << '\n';
  cout << "o2: " << o2.getx() << '\n';

  return 0;
}