Sharp Tutorial
function and constructor overloading

Python

Java

C

C++

HTML/CSS

Java Script

PHP

SQL

C Programs

introduction to c++

  • C++ Home
  • Introduction to C++
  • History features
  • Sample Programs
  • cout , cin , endl
  • Data type and Operators
  • if else in c++
  • loop in c++

Oops in C++

  • Object / Class
  • Constructor
  • Function & Constructor Overloading
  • Inheritance
  • Overriding

Advanced C++

  • Strings in C++
  • Exception Handling
  • Special Functions
  • C++ Programs

overloading in c++

In C++ function or constructor may be overloaded. Overloading is done when in the same class there are multiple functions with the same name but different signature.

We can overload the user defined functions as well as the constructors. Overloading can not be done based on the return type of the function, it can be done either on no of arguments or order of the arguments

Function Overloading A class with two display functions

#include<iostream>
using namespace std;
class A
{
public:
int rollNo;
string name;
void display(string n) // parameterized function
{
cout<<"Hello Mr " <<n;
name=n;
}
void display()
{
cout<<"Hello Mr Default Kumar";
}
};

 

in the Above example a class has two functions display with same name but arguments are different so if no argument is passed then second function is being called if we pass a single argument then first function is being called.

Constructor Overloading Demo Class A with two constructors

#include<iostream>
using namespace std;
class A
{
public:
string name;
A(string n) // parameterized constructor
{
cout<<"Hello Mr " <<n;
name=n;
}
A() // default constructor
{
cout<<"Hello Mr Default Kumar";
}
};

 

 

Function Overloading complete Example

#include<iostream>
using namespace std;
class Box
{
public:
int area;
int areaCal(int l, int b)
{
area=l*b;
return area;
}
int areaCal(int s)
{
area=s*s;
return area;
}
};
int main()
{
int l,b,area;
cout<<"enter length and breadth of box";
cin>>l;
cin>>b;
Box b1;
area=b1.areaCal(l,b);
cout<<"area of the rectangle box is"<<area;
int side;
cout<<"enter the side of the square";
cin>>side;
area=b1.areaCal(side);
cout<<"area of square box is"<<area;
return 0;
}

 

From the above program the following output is being generated.

Enquiry about Course

Ask your Question

Click Here

Sharp (2) Tutorials

Video/ C Introduction

Watch video in full size

Video tutorial

Follow by Email
Facebook
Facebook
fb-share-icon
YouTube
Copyright © Sharp Tutorial
Build with WordPress
Wordpress Social Share Plugin powered by Ultimatelysocial
Sharp Tutorial