CPP Advance Methods

Advance Methods and functions


What is Method Overloading?
  • In C++ you can create several methods in a class with the same name. We says that these methods overload each other.
  • The class destructor method is the only one that cannot be overloaded.
  • C++ require that those methods must differ in their parameter list with a different type of parameter, a different number of parameters or both.
    Overload Method example:
    Source code Result
    #include <iostream>
    
    class Sylinder {
    public:
      // example of overloaded Constructors
      Sylinder(int radius,int height ) {
        this->radius = radius;
        this->height = height; }
      // Constructor with no parameter 
      // is called default Constructor 
      Sylinder() { radius=2; height=5; }
    
      ~Sylinder() {}
      // example of overloaded methods;  setRadius
      void setRadius(Sylinder & sylinder) {
        setRadius(sylinder.getRadius()); }
      void setRadius(int radius) {this->radius = radius;}
      int getRadius() const {return radius; }
      void setHeight(int height) {this->height = height;}
      int getHeight()  {return height;}
      // Using default values
      void setRadiusAndHeight(int radius,int height=40 ) {
        this->radius = radius;
        this->height = height; }
    private:
      int radius;
      int height;
    };
    
    using namespace std;
    
    int main(){
      Sylinder * pSyl =  new Sylinder;
      cout << "pSyl radius: " << pSyl->getRadius()
        << " meter"  << endl;
    
      pSyl->setRadius(10);
      cout << "pSyl radius: " << pSyl->getRadius()
        << " meter"  << endl;
    
      Sylinder newSyl(4,20);
      pSyl->setRadius(newSyl);
      cout << "pSyl radius: " << pSyl->getRadius()
        << " meter"  << endl;
    
      return 0;
    }
    pSyl radius: 2 meter
    pSyl radius: 10 meter
    pSyl radius: 4 meter

  • Methods can as Function also have default values after the same rules as for functions. An example is shown in the Source code above for the setRadiusAndHeight method.
  • Constructors are invoked in two stages: the initialization stage and the body.

© 2010 by Finnesand Data. All rights reserved.
This site aims to provide FREE programming training and technics.
Finnesand Data as site owner gives no warranty for the correctness in the pages or source codes.
The risk of using this web-site pages or any program codes from this website is entirely at the individual user.