1.sample code box:.
#include <iostream>
using namespace std;
int main()
cout << "Hello World";
return 0;
2.Following is the example, which will produce correct size of various
data types on your computer.
#include <iostream>
using namespace std;
int main()
cout << "Size of char : " << sizeof(char) << endl;
cout << "Size of int : " << sizeof(int) << endl;
cout << "Size of short int : " << sizeof(short int) << endl;
cout << "Size of long int : " << sizeof(long int) << endl;
cout << "Size of float : " << sizeof(float) << endl;
cout << "Size of double : " << sizeof(double) << endl;
cout << "Size of wchar_t : " << sizeof(wchar_t) << endl;
return 0;
}
3.Following is the example using local variables:
#include <iostream>
using namespace std;
int main ()
// Local variable declaration:
int a, b;
int c;
// actual initialization
a = 10;
b = 20;
c = a + b;
cout << c;
return 0;
4 Following is the example using global and local variables:
#include <iostream>
using namespace std;
// Global variable declaration:
int g;
int main ()
{
// Local variable declaration:
int a, b;
// actual initialization
a = 10;
b = 20;
g = a + b;
cout << g;
return 0;
5.Following example explains it in detail:
#include <iostream>
using namespace std;
#define LENGTH 10
#define WIDTH 5
#define NEWLINE '\n'
int main()
int area;
area = LENGTH * WIDTH;
cout << area;
cout << NEWLINE;
return 0;
}
6.In the following example, the declaration of the variable X hides the
class type X, but you can still use the static class member count by
qualifying it with the class type X and the scope resolution operator.
#include <iostream>
using namespace std;
class X
public:
static int count;
};
int X::count = 10; // define static data member
int main ()
int X = 0; // hides class type X
cout << X::count << endl; // use static member of class X
7. Break For example, let's stop the countdown before its natural end:
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16
// break loop example
#include <iostream>
using namespace std;
int main ()
{
for (int n=10; n>0; n--)
cout << n << ", ";
if (n==3)
cout << "countdown aborted!";
break;
10, 9, 8, 7, 6, 5, 4, 3, countdown aborted!
8. Continue Statement For example, let's skip number 5 in our
countdown:
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16
// continue loop example
#include <iostream>
using namespace std;
int main ()
for (int n=10; n>0; n--) {
if (n==5) continue;
cout << n << ", ";
}
cout << "liftoff!\n";
10, 9, 8, 7, 6, 4, 3, 2, 1, liftoff!
9. an example, here is a version of our countdown loop using goto:
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16
// goto loop example
#include <iostream>
using namespace std;
int main ()
int n=10;
mylabel:
cout << n << ", ";
n--;
if (n>0) goto mylabel;
cout << "liftoff!\n";
10, 9, 8, 7, 6, 5, 4, 3, 2, 1, liftoff!
10.For example: Functions program.
#include <iostream>
using namespace std;
// function declaration
int max(int num1, int num2);
int main ()
// local variable declaration:
int a = 100;
int b = 200;
int ret;
// calling a function to get max value.
ret = max(a, b);
cout << "Max value is : " << ret << endl;
return 0;
// function returning the max between two numbers
int max(int num1, int num2)
// local variable declaration
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
11. Inline function Following is an example, which makes use of inline
function to return max of two numbers:
#include <iostream>
using namespace std;
inline int Max(int x, int y)
return (x > y)? x : y;
// Main function for the program
int main( )
cout << "Max (20,10): " << Max(20,10) << endl;
cout << "Max (0,200): " << Max(0,200) << endl;
cout << "Max (100,1010): " << Max(100,1010) << endl;
return 0;
12. Fuction overloading Following is the example where same function
print() is being used to print different data types:
#include <iostream>
using namespace std;
class printData
{
public:
void print(int i) {
cout << "Printing int: " << i << endl;
void print(double f) {
cout << "Printing float: " << f << endl;
void print(char* c) {
cout << "Printing character: " << c << endl;
};
int main(void)
printData pd;
// Call print to print integer
pd.print(5);
// Call print to print float
pd.print(500.263);
// Call print to print character
pd.print("Hello C++");
return 0;
}
13.Passing array to the functions:
#include <iostream>
using namespace std;
void printarray (int arg[], int length) {
for (int n = 0; n < length; n++) {
cout << arg[n] << " ";
cout << "\n";
int main ()
int firstarray[] = {5, 10, 15};
int secondarray[] = {2, 4, 6, 8, 10};
printarray(firstarray, 3);
printarray(secondarray, 5);
return 0;
14.passing array to the function
et us call the above function as follows:
#include <iostream>
using namespace std;
// function declaration:
double getAverage(int arr[], int size);
int main ()
// an int array with 5 elements.
int balance[5] = {1000, 2, 3, 17, 50};
double avg;
// pass pointer to the array as an argument.
avg = getAverage( balance, 5 ) ;
// output the returned value
cout << "Average value is: " << avg << endl;
return 0;
15. two dimensional array:
#include <iostream>
using namespace std;
int main ()
// an array with 5 rows and 2 columns.
int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}};
// output each array element's value
for ( int i = 0; i < 5; i++ )
for ( int j = 0; j < 2; j++ )
cout << "a[" << i << "][" << j << "]: ";
cout << a[i][j]<< endl;
return 0;
16:operator be applied twice, as is shown below in the example:
#include <iostream>
using namespace std;
int main ()
int var;
int *ptr;
int **pptr;
var = 3000;
// take the address of var
ptr = &var;
// take the address of ptr using address of operator &
pptr = &ptr;
// take the value using pptr
cout << "Value of var :" << var << endl;
cout << "Value available at *ptr :" << *ptr << endl;
cout << "Value available at **pptr :" << **pptr << endl;
return 0;
When the above code is compiled and executed, it produces the following
result:
Value of var :3000
Value available at *ptr :3000
Value available at **pptr :3000
17: Following example makes use of references on int and double:
#include <iostream>
using namespace std;
int main ()
// declare simple variables
int i;
double d;
// declare reference variables
int& r = i;
double& s = d;
i = 5;
cout << "Value of i : " << i << endl;
cout << "Value of i reference : " << r << endl;
d = 11.7;
cout << "Value of d : " << d << endl;
cout << "Value of d reference : " << s << endl;
return 0;
When the above code is compiled together and executed, it produces the
following result:
Value of i : 5
Value of i reference : 5
Value of d : 11.7
Value of d reference : 11.7
18:example of call by reference which makes use of C++ reference:
#include <iostream>
using namespace std;
// function declaration
void swap(int& x, int& y);
int main ()
// local variable declaration:
int a = 100;
int b = 200;
cout << "Before swap, value of a :" << a << endl;
cout << "Before swap, value of b :" << b << endl;
/* calling a function to swap the values.*/
swap(a, b);
cout << "After swap, value of a :" << a << endl;TUTORIALS POINT
Simply Easy Learning
cout << "After swap, value of b :" << b << endl;
return 0;
// function definition to swap the values.
void swap(int& x, int& y)
int temp;
temp = x; /* save the value at address x */
x = y; /* put y into x */
y = temp; /* put x into y */
return;
When the above code is compiled and executed, it produces the following
result:
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :200
After swap, value of b :100
19: a function can be used on the left side of an assignment statement.
For example, consider this simple program:
#include <iostream>
#include <ctime>
using namespace std;
double vals[] = {10.1, 12.6, 33.1, 24.1, 50.0};
double& setValues( int i )
return vals[i]; // return a reference to the ith element
// main function to call above defined function.
int main ()
cout << "Value before change" << endl;
for ( int i = 0; i < 5; i++ )
cout << "vals[" << i << "] = ";
cout << vals[i] << endl;
setValues(1) = 20.23; // change 2nd element
setValues(3) = 70.8; // change 4th element
cout << "Value after change" << endl;
for ( int i = 0; i < 5; i++ ) {
cout << "vals[" << i << "] = ";
cout << vals[i] << endl;
return 0;
When the above code is compiled together and executed, it produces the
following result:
Value before change
vals[0] = 10.1
vals[1] = 12.6
vals[2] = 33.1
vals[3] = 24.1
vals[4] = 50
20:Consider the following program: Friend Function
#include <iostream>
using namespace std;
class Box
double width;
public:
friend void printWidth( Box box );
void setWidth( double wid );
};
// Member function definition
void Box::setWidth( double wid )
width = wid;
// Note: printWidth() is not a member function of any class.
void printWidth( Box box )
/* Because setWidth() is a friend of Box, it can
directly access any member of this class */
cout << "Width of box : " << box.width <<endl;
// Main function for the program
int main( )
Box box;
// set box width without member function
box.setWidth(10.0);
// Use friend function to print the wdith.
printWidth( box );
return 0;
21: Public Member You can set and get the value of public variables
without any member function as shown in the following example:
#include <iostream>
using namespace std;
class Line
public:
double length;
void setLength( double len );
double getLength( void );
};
// Member functions definitions
double Line::getLength(void)
return length ;
void Line::setLength( double len )
length = len;
}
// Main function for the program
int main( )
Line line;
// set line length
line.setLength(6.0);
cout << "Length of line : " << line.getLength() <<endl;
// set line length without member function
line.length = 10.0; // OK: because length is public
cout << "Length of line : " << line.length <<endl;
return 0;
When the above code is compiled and executed, it produces the following
result:
Length of line : 6
Length of line : 10
22:Private Member :we define data in private section and related
functions in public section so that they can be called from outside of the
class as shown in the following program.
#include <iostream>
using namespace std;
class Box
{
public:
double length;
void setWidth( double wid );
double getWidth( void );
private:
double width;
};
// Member functions definitions
double Box::getWidth(void)
return width ;
void Box::setWidth( double wid )
width = wid;
// Main function for the program
int main( )
Box box;
// set box length without member function
box.length = 10.0; // OK: because length is public
cout << "Length of box : " << box.length <<endl;
// set box width without member function
// box.width = 10.0; // Error: because width is private
box.setWidth(10.0); // Use member function to set it.
cout << "Width of box : " << box.getWidth() <<endl;
return 0;
When the above code is compiled and executed, it produces the following
result:
Length of box : 10
Width of box : 10
23:Protected member Following example is similar to above example
and here width member will be accessible by any member function of its
derived class SmallBox.
using namespace std;
class Box
protected:
double width;
};
class SmallBox:Box // SmallBox is the derived class.
public:
void setSmallWidth( double wid );
double getSmallWidth( void );
};
// Member functions of child class
double SmallBox::getSmallWidth(void)
return width ;
void SmallBox::setSmallWidth( double wid )
width = wid;
// Main function for the program
int main( )
SmallBox box;
// set box width using member function
box.setSmallWidth(5.0);
cout << "Width of box : "<< box.getSmallWidth() << endl;
return 0;
When the above code is compiled and executed, it produces the following
result:
Width of box : 5
24:Accessing Data Member Let us try following example to make the
things clear:
#include <iostream>
using namespace std;
class Box
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
int main( )
Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box
double volume = 0.0; // Store the volume of a box here
// box 1 specification
Box1.height = 5.0;
Box1.length = 6.0;
Box1.breadth = 7.0;
// box 2 specification
Box2.height = 10.0;
Box2.length = 12.0;
Box2.breadth = 13.0;
// volume of box 1
volume = Box1.height * Box1.length * Box1.breadth;
cout << "Volume of Box1 : " << volume <<endl;
// volume of box 2
volume = Box2.height * Box2.length * Box2.breadth;
cout << "Volume of Box2 : " << volume <<endl;
return 0;
When the above code is compiled and executed, it produces the following
result:
Volume of Box1 : 210
Volume of Box2 : 1560
25: Let us put above concepts to set and get the value of different class
members in a class:
#include <iostream>
using namespace std;
class Box
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
// Member functions declaration
double getVolume(void);
void setLength( double len );
void setBreadth( double bre );
void setHeight( double hei );
};
// Member functions definitions
double Box::getVolume(void)
return length * breadth * height;
void Box::setLength( double len )
length = len;
void Box::setBreadth( double bre )
breadth = bre;
void Box::setHeight( double hei )
{
height = hei;
// Main function for the program
int main( )
{
Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box
double volume = 0.0; // Store the volume of a box here
// box 1 specification
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);
// box 2 specification
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);
// volume of box 1
volume = Box1.getVolume();
cout << "Volume of Box1 : " << volume <<endl;
// volume of box 2
volume = Box2.getVolume();
cout << "Volume of Box2 : " << volume <<endl;
return 0;
}
When the above code is compiled and executed, it produces the following
result:
Volume of Box1 : 210
Volume of Box2 : 1560
26:Following example explains the concept of constructor:
#include <iostream>
using namespace std;
class Line
public:
void setLength( double len );
double getLength( void );
Line(); // This is the constructor
private:
double length;
};
// Member functions definitions including constructor
Line::Line(void)
cout << "Object is being created" << endl;
void Line::setLength( double len )
{
length = len;
double Line::getLength( void )
return length;
// Main function for the program
int main( )
Line line;
// set line length
line.setLength(6.0);
cout << "Length of line : " << line.getLength() <<endl;
return 0;
When the above code is compiled and executed, it produces the following
result:
Object is being created
Length of line : 6
27: Parametrized Constructor: This helps you to assign initial value to an
object at the time of its creation as shown in the following example:
#include <iostream>
using namespace std;
class Line
public:
void setLength( double len );
double getLength( void );
Line(double len); // This is the constructor
private:
double length;
};
// Member functions definitions including constructor
Line::Line( double len)
cout << "Object is being created, length = " << len << endl;
length = len;
void Line::setLength( double len )
length = len;
double Line::getLength( void )
{
return length;
// Main function for the program
int main( )
Line line(10.0);
// get initially set length.
cout << "Length of line : " << line.getLength() <<endl;
// set line length again
line.setLength(6.0);
cout << "Length of line : " << line.getLength() <<endl;
return 0;
When the above code is compiled and executed, it produces the following
result:
Object is being created, length = 10
Length of line : 10
Length of line : 6
28: Destructor: Following example explains the concept of destructor:
#include <iostream>
using namespace std;
class Line
{
public:
void setLength( double len );
double getLength( void );
Line(); // This is the constructor declaration
~Line(); // This is the destructor: declaration
private:
double length;
};
// Member functions definitions including constructor
Line::Line(void)
cout << "Object is being created" << endl;
Line::~Line(void)
cout << "Object is being deleted" << endl;
void Line::setLength( double len )
length = len;
double Line::getLength( void )
{
return length;
// Main function for the program
int main( )
Line line;
// set line length
line.setLength(6.0);
cout << "Length of line : " << line.getLength() <<endl;
return 0;
When the above code is compiled and executed, it produces the following
result:
Object is being created
Length of line : 6
Object is being deleted
29:Constructors Overloading examples
#include <iostream.h>
class Overclass
public:
int x;
int y;
Overclass() { x = y = 0; }
Overclass(int a) { x = y = a; }
Overclass(int a, int b) { x = a; y = b; }
};
int main()
Overclass A;
Overclass A1(4);
Overclass A2(8, 12);
cout << "Overclass A's x,y value:: " <<
A.x << " , "<< A.y << "\n";
cout << "Overclass A1's x,y value:: "<<
A1.x << " ,"<< A1.y << "\n";
cout << "Overclass A2's x,y value:; "<<
A2.x << " , "<< A2.y << "\n";
return 0;
Result:
Overclass A's x,y value:: 0 , 0
Overclass A1's x,y value:: 4 ,4
Overclass A2's x,y value:; 8 , 12
30: Copy Costructor and Destructors:
#include <iostream>
using namespace std;
class Line
public:
int getLength( void );
Line( int len ); // simple constructor
Line( const Line &obj); // copy constructor
~Line(); // destructor
private:
int *ptr;
};
// Member functions definitions including constructor
Line::Line(int len)
cout << "Normal constructor allocating ptr" << endl;
// allocate memory for the pointer;
ptr = new int;
*ptr = len;
Line::Line(const Line &obj)
{
cout << "Copy constructor allocating ptr." << endl;
ptr = new int;
*ptr = *obj.ptr; // copy the value
Line::~Line(void)
cout << "Freeing memory!" << endl;
delete ptr;
int Line::getLength( void )
return *ptr;
void display(Line obj)
cout << "Length of line : " << obj.getLength() <<endl;
// Main function for the program
int main( )
Line line(10);
display(line);
return 0;
When the above code is compiled and executed, it produces the following
result:
Normal constructor allocating ptr
Copy constructor allocating ptr.
Length of line : 10
Freeing memory!
Freeing memory!
31:Let us try the following example to understand the concept of static
data members:
#include <iostream>
using namespace std;
class Box
public:
static int objectCount;
// Constructor definition
Box(double l=2.0, double b=2.0, double h=2.0)
cout <<"Constructor called." << endl;
length = l;
breadth = b;
height = h;
// Increase every time object is created
objectCount++;
double Volume()
return length * breadth * height;
private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
// Initialize static member of class Box
int Box::objectCount = 0;
int main(void)
Box Box1(3.3, 1.2, 1.5); // Declare box1
Box Box2(8.5, 6.0, 2.0); // Declare box2
// Print total number of objects.
cout << "Total objects: " << Box::objectCount << endl;
return 0;
When the above code is compiled and executed, it produces the following
result:
Constructor called.
Constructor called.
Total objects: 2
32:Let us try the following example to understand the concept of static
function members:
#include <iostream>
using namespace std;
class Box
public:
static int objectCount;
// Constructor definition
Box(double l=2.0, double b=2.0, double h=2.0)
cout <<"Constructor called." << endl;
length = l;
breadth = b;
height = h;
// Increase every time object is created
objectCount++;
double Volume()
return length * breadth * height;
static int getCount()
return objectCount;
private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
// Initialize static member of class Box
int Box::objectCount = 0;
int main(void)
// Print total number of objects before creating object.
cout << "Inital Stage Count: " << Box::getCount() << endl;
Box Box1(3.3, 1.2, 1.5); // Declare box1
Box Box2(8.5, 6.0, 2.0); // Declare box2
// Print total number of objects after creating object.
cout << "Final Stage Count: " << Box::getCount() << endl;
return 0;
When the above code is compiled and executed, it produces the following
result:
Inital Stage Count: 0
Constructor called.
Constructor called.
Final Stage Count: 2
33: Pointers to Objects : lets see the example of student that wiil clear
your idea about this topic
#include <iostream>
#include <string>
using namespace std;
class student
private:
int rollno;
string name;
public:
student():rollno(0),name("")
{}
student(int r, string n): rollno(r),name (n)
{}
void get()
cout<<"enter roll no";
cin>>rollno;
cout<<"enter name";
cin>>name;
void print()
cout<<"roll no is "<<rollno;
cout<<"name is "<<name;
};
void main ()
student *ps=new student;
(*ps).get();
(*ps).print();
delete ps;
}
34: Unary operator overloading (-) Following example explains how
minus (-) operator can be overloaded for prefix as well as postfix usage.
#include <iostream>
using namespace std;
class Distance
private:
int feet; // 0 to infinite
int inches; // 0 to 12
public:
// required constructors
Distance(){
feet = 0;
inches = 0;
Distance(int f, int i){
feet = f;
inches = i;
// method to display distance
void displayDistance()
{
cout << "F: " << feet << " I:" << inches <<endl;
// overloaded minus (-) operator
Distance operator- ()
feet = -feet;
inches = -inches;
return Distance(feet, inches);
};
int main()
Distance D1(11, 10), D2(-5, 11);
-D1; // apply negation
D1.displayDistance(); // display D1
-D2; // apply negation
D2.displayDistance(); // display D2
return 0;
When the above code is compiled and executed, it produces the following
result:
F: -11 I:-10
F: 5 I:-11
35: Following example explain how addition (+) operator can be
overloaded. Similar way, you can overload subtraction (-) and division (/)
operators.
#include <iostream>
using namespace std;
class Box
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
public:
double getVolume(void)
return length * breadth * height;
void setLength( double len )
length = len;
void setBreadth( double bre )
breadth = bre;
}
void setHeight( double hei )
height = hei;
// Overload + operator to add two Box objects.
Box operator+(const Box& b)
Box box;
box.length = this->length + b.length;
box.breadth = this->breadth + b.breadth;
box.height = this->height + b.height;
return box;
};
// Main function for the program
int main( )
Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box
Box Box3; // Declare Box3 of type Box
double volume = 0.0; // Store the volume of a box here
// box 1 specification
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);
// box 2 specification
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);
// volume of box 1
volume = Box1.getVolume();
cout << "Volume of Box1 : " << volume <<endl;
// volume of box 2
volume = Box2.getVolume();
cout << "Volume of Box2 : " << volume <<endl;
// Add two object as follows:
Box3 = Box1 + Box2;
// volume of box 3
volume = Box3.getVolume();
cout << "Volume of Box3 : " << volume <<endl;
return 0;
When the above code is compiled and executed, it produces the following
result:
Volume of Box1 : 210
Volume of Box2 : 1560
Volume of Box3 : 5400
36:Following example explain how a < operator can be overloaded and
similar way you can overload other relational operators.
#include <iostream>
using namespace std;
class Distance
private:
int feet; // 0 to infinite
int inches; // 0 to 12
public:
// required constructors
Distance(){
feet = 0;
inches = 0;
Distance(int f, int i){
feet = f;
inches = i;
// method to display distance
void displayDistance()
{
cout << "F: " << feet << " I:" << inches <<endl;
// overloaded minus (-) operator
Distance operator- ()
feet = -feet;
inches = -inches;
return Distance(feet, inches);
// overloaded < operator
bool operator <(const Distance& d)
if(feet < d.feet)
return true;
if(feet == d.feet && inches < d.inches)
return true;
return false;
}
};
int main()
Distance D1(11, 10), D2(5, 11);
if( D1 < D2 )
cout << "D1 is less than D2 " << endl;
else
cout << "D2 is less than D1 " << endl;
return 0;
When the above code is compiled and executed, it produces the following
result:
D2 is less than D1
37: Following example explain how increment (++) operator can be
overloaded for prefix as well as postfix usage. Similar way you can
overload operator (--).
#include <iostream>
using namespace std;
class Time
private:
int hours; // 0 to 23
int minutes; // 0 to 59
public:
// required constructors
Time(){
hours = 0;
minutes = 0;
Time(int h, int m){
hours = h;
minutes = m;
// method to display time
void displayTime()
cout << "H: " << hours << " M:" << minutes <<endl;
// overloaded prefix ++ operator
Time operator++ ()
{
++minutes; // increment this object
if(minutes >= 60)
++hours;
minutes -= 60;
return Time(hours, minutes);
// overloaded postfix ++ operator
Time operator++( int )
// save the orignal value
Time T(hours, minutes);
// increment this object
++minutes;
if(minutes >= 60)
++hours;
minutes -= 60;
// return old original value
return T;
};
int main()
Time T1(11, 59), T2(10,40);
++T1; // increment T1
T1.displayTime(); // display T1
++T1; // increment T1 again
T1.displayTime(); // display T1
T2++; // increment T2
T2.displayTime(); // display T2
T2++; // increment T2 again
T2.displayTime(); // display T2
return 0;
When the above code is compiled and executed, it produces the following
result:
H: 12 M:0
H: 12 M:1
H: 10 M:41
H: 10 M:42
38:Overloadind using Friend function
#include <iostream>
using namespace std;
class Point {
int x, y;
public:
Point() {} // needed to construct temporaries
Point(int px, int py) {
x = px;
y = py;
void show() {
cout << x << " ";
cout << y << "\n";
friend Point operator+(Point op1, Point op2); // now a friend
Point operator-(Point op2);
Point operator=(Point op2);
Point operator++();
};
// Now, + is overloaded using friend function.
Point operator+(Point op1, Point op2)
{
Point temp;
temp.x = op1.x + op2.x;
temp.y = op1.y + op2.y;
return temp;
// Overload - for Point.
Point Point::operator-(Point op2)
Point temp;
// notice order of operands
temp.x = x - op2.x;
temp.y = y - op2.y;
return temp;
// Overload assignment for Point.
Point Point::operator=(Point op2)
x = op2.x;
y = op2.y;
return *this; // i.e., return object that generated call
// Overload ++ for Point.
Point Point::operator++()
x++;
y++;
return *this;
int main()
Point ob1(10, 20), ob2( 5, 30);
ob1 = ob1 + ob2;
ob1.show();
return 0;
out put: 15 50
39:Following example explain how an assignment operator can be
overloaded.
#include <iostream>
using namespace std;
class Distance
private:
int feet; // 0 to infinite
int inches; // 0 to 12
public:
// required constructors
Distance(){
feet = 0;
inches = 0;
Distance(int f, int i){
feet = f;
inches = i;
void operator=(const Distance &D )
feet = D.feet;
inches = D.inches;
// method to display distance
void displayDistance()
cout << "F: " << feet << " I:" << inches << endl;
};
int main()
Distance D1(11, 10), D2(5, 11);
cout << "First Distance : ";
D1.displayDistance();
cout << "Second Distance :";
D2.displayDistance();
// use assignment operator
D1 = D2;
cout << "First Distance :";
D1.displayDistance();
return 0;
When the above code is compiled and executed, it produces the following
result:
First Distance : F: 11 I:10
Second Distance :F: 5 I:11
First Distance :F: 5 I:11
40: Let us try the following example to understand the concept of This
pointer:
#include <iostream>
using namespace std;
class Box
{
public:
// Constructor definition
Box(double l=2.0, double b=2.0, double h=2.0)
cout <<"Constructor called." << endl;
length = l;
breadth = b;
height = h;
double Volume()
return length * breadth * height;
int compare(Box box)
return this->Volume() > box.Volume();
private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
int main(void)
Box Box1(3.3, 1.2, 1.5); // Declare box1
Box Box2(8.5, 6.0, 2.0); // Declare box2
if(Box1.compare(Box2))
cout << "Box2 is smaller than Box1" <<endl;
else
cout << "Box2 is equal to or larger than Box1" <<endl;
return 0;
When the above code is compiled and executed, it produces the following
result:
Constructor called.
Constructor called.
Box2 is equal to or larger than Box1
41: Following example explains how extraction operator >> and
insertion operator <<.
#include <iostream>
using namespace std;
class Distance
private:
int feet; // 0 to infinite
int inches; // 0 to 12
public:
// required constructors
Distance(){
feet = 0;
inches = 0;
Distance(int f, int i){
feet = f;
inches = i;
friend ostream &operator<<( ostream &output,
const Distance &D )
output << "F : " << D.feet << " I : " << D.inches;
return output;
}
friend istream &operator>>( istream &input, Distance &D )
input >> D.feet >> D.inches;
return input;
};
int main()
Distance D1(11, 10), D2(5, 11), D3;
cout << "Enter the value of object : " << endl;
cin >> D3;
cout << "First Distance : " << D1 << endl;
cout << "Second Distance :" << D2 << endl;
cout << "Third Distance :" << D3 << endl;
return 0;
When the above code is compiled and executed, it produces the following
result:
$./a.out
Enter the value of object :
70
10
First Distance : F : 11 I : 10
Second Distance :F : 5 I : 11
Third Distance :F : 70 I : 10
42:Inheritance Consider a base class Shape and its derived class
Rectangle as follows:
#include <iostream>
using namespace std;
// Base class
class Shape
public:
void setWidth(int w)
width = w;
void setHeight(int h)
height = h;
protected:
int width;
int height;
};
// Derived class
class Rectangle: public Shape
public:
int getArea()
return (width * height);
};
int main(void)
Rectangle Rect;
Rect.setWidth(5);
Rect.setHeight(7);
// Print the area of the object.
cout << "Total area: " << Rect.getArea() << endl;
return 0;
When the above code is compiled and executed, it produces the following
result:
Total area: 35
43: Multiple Inheritance: Let us try the following example:
#include <iostream>
using namespace std;
// Base class Shape
class Shape
public:
void setWidth(int w)
width = w;
void setHeight(int h)
height = h;
protected:
int width;
int height;
};
// Base class PaintCost
class PaintCost
public:
int getCost(int area)
{
return area * 70;
};
// Derived class
class Rectangle: public Shape, public PaintCost
public:
int getArea()
return (width * height);
};
int main(void)
Rectangle Rect;
int area;
Rect.setWidth(5);
Rect.setHeight(7);
area = Rect.getArea();
// Print the area of the object.
cout << "Total area: " << Rect.getArea() << endl;
// Print the total cost of painting
cout << "Total paint cost: $" << Rect.getCost(area) << endl;
return 0;
When the above code is compiled and executed, it produces the following
result:
Total area: 35
Total paint cost: $2450
44:Following example further explains concept of inheritance :
class Shape
protected:
float width, height;
public:
void set_data (float a, float b)
width = a;
height = b;
};
class Rectangle: public Shape
public:
float area ()
return (width * height);
};
class Triangle: public Shape
public:
float area ()
return (width * height / 2);
};
int main ()
Rectangle rect;
Triangle tri;
rect.set_data (5,3);
tri.set_data (2,5);
cout << rect.area() << endl;
cout << tri.area() << endl;
return 0;
}
output :
15
45:Overriding and hiding a base class method in a derived class?
#include <iostream>
#include <cstring>
class Person {
public:
Person (int age, int weight){
std::cout << "Person constructor ...\n";
this->age = age;
this->weight = weight;
~Person() {
std::cout << "Person destructor ...\n";
// this method is overrided in the drived class
void showInfo() {
std::cout << "I am " << age << " years old " ;
std::cout << "and weighs " << weight << " kilo.\n\n" ;
}
// this method is hided
void showInfo(std::string pname) {
std::cout << "I am " << pname.c_str() << " " << age << " years old " ;
std::cout << "and weighs " << weight << " kilo.\n\n" ;
int getAge() { return age; }
int getWeight() { return weight; }
protected:
int age;
private:
int weight;
};
class Employee : public Person {
public:
Employee (int age, int weight, int salary): Person(age,weight){
std::cout << "Employee constructor ...\n";
this->salary = salary;
~Employee() {
std::cout << "Employee destructor ...\n";
// This method override the class method : void showInfo();
void showInfo() {
// Drived class can only access protected members in base class
// as long as Inheritance access specifier is pucblic or protected.
std::cout << "I am " << age << " years old " ;
std::cout << "and weighs " << getWeight() << " kilo " ;
std::cout << "and earns " << salary << " dollar.\n\n" ;
// access hided method inside the drived class
Person::showInfo("an Employee");
int getSalary() { return salary; }
private:
int salary;
};
int main()
int age=40;
int weight=70;
Person * pRicard = new Person(age, weight);
pRicard->showInfo();
// access hided method outside the class
pRicard->Person::showInfo("a Person");
delete pRicard;
Employee * pObama = new Employee(45, 65, 50000);
pObama->showInfo();
delete pObama;
return 0;
When we run this application, the result will be:
Person constructor ...
I am 40 years old and weighs 70 kilo.
I am a Person 40 years old and weighs 70 kilo.
Person destructor ...
Person constructor ...
Employee constructor ...
I am 45 years old and weighs 65 kilo and earns 50000 dollar.
I am an Employee 45 years old and weighs 65 kilo.
Employee destructor ...
Person destructor ...
46:Polymorphism: Consider the following example where a base class
has been derived by other two classes:
#include <iostream>
using namespace std;
class Shape {
protected:
int width, height;
public:
Shape( int a=0, int b=0)
width = a;
height = b;
int area()
cout << "Parent class area :" <<endl;
return 0;
};
class Rectangle: public Shape{
public:
Rectangle( int a=0, int b=0)
Shape(a, b);
int area ()
cout << "Rectangle class area :" <<endl;
return (width * height);
}
};
class Triangle: public Shape{
public:
Triangle( int a=0, int b=0)
Shape(a, b);
int area ()
cout << "Rectangle class area :" <<endl;
return (width * height / 2);
};
// Main function for the program
int main( )
Shape *shape;
Rectangle rec(10,7);
Triangle tri(10,5);
// store the address of Rectangle
shape = &rec;
// call rectangle area.
shape->area();
// store the address of Triangle
shape = &tri;
// call triangle area.
shape->area();
return 0;
When the above code is compiled and executed, it produces the following
result:
Parent class area
Parent class area
47:Virtual function: the keyword virtual so that it looks like this:
class Shape {
protected:
int width, height;
public:
Shape( int a=0, int b=0)
width = a;
height = b;
virtual int area()
{
cout << "Parent class area :" <<endl;
return 0;
};
After this slight modification, when the previous example code is compiled
and executed, it produces the following result:
Rectangle class area
Triangle class area
48:We can change the virtual function area() in the base class to the
following:
class Shape {
protected:
int width, height;
public:
Shape( int a=0, int b=0)
width = a;
height = b;
// pure virtual function
virtual int area() = 0;
};
The = 0 tells the compiler that the function has no body and above virtual
function will be called pure virtual function
49:Data Abstraction Example: Any C++ program where you implement a
class with public and private members is an example of data abstraction.
Consider the following example:
#include <iostream>
using namespace std;
class Adder{
public:
// constructor
Adder(int i = 0)
total = i;
// interface to outside world
void addNum(int number)
total += number;
// interface to outside world
int getTotal()
return total;
};
private:
// hidden data from outside world
int total;
};
int main( )
Adder a;
a.addNum(10);
a.addNum(20);
a.addNum(30);
cout << "Total " << a.getTotal() <<endl;
return 0;
When the above code is compiled and executed, it produces the following
result:
Total 60
50:Virtual Base Class: Consider following example:
class A
{
public:
int i;
};
class B : virtual public A
{
public:
int j;
};
class C: virtual public A
{
public:
int k;
};
class D: public B, public C
{
public:
int sum;
};
int main()
{
D ob;
ob.i = 10; //unambiguous since only one copy of i is inherited.
ob.j = 20;
ob.k = 30;
ob.sum = ob.i + ob.j + ob.k;
cout << “Value of i is : ”<< ob.i<<”\n”;
cout << “Value of j is : ”<< ob.j<<”\n”; cout << “Value of k is :”<<
ob.k<<”\n”;
cout << “Sum is : ”<< ob.sum <<”\n”;
return 0;
}.
51: i/o examples: The cerr is also used in conjunction with the
stream insertion operator as shown in the following example.
#include <iostream>
using namespace std;
int main( )
{
char str[] = "Unable to read....";
cerr << "Error message : " << str << endl;
}
When the above code is compiled and executed, it produces the
following result:
Error message : Unable to read....
52:The clog is also used in conjunction with the stream
insertion operator as shown in the following example.
#include <iostream>
using namespace std;
int main( )
{
char str[] = "Unable to read....";
clog << "Error message : " << str << endl;
}
When the above code is compiled and executed, it produces the
following result:
Error message : Unable to read....
53:Read & Write Example:Following is the C++ program which
opens a file in reading and writing mode. After writing
information inputted by the user to a file named afile.dat, the
program reads information from the file and outputs it onto the
screen:
#include <fstream>
#include <iostream>
using namespace std;
int main ()
{
char data[100];
// open a file in write mode.
ofstream outfile;
outfile.open("afile.dat");
cout << "Writing to the file" << endl;
cout << "Enter your name: ";
cin.getline(data, 100);
// write inputted data into the file.
outfile << data << endl;
cout << "Enter your age: ";
cin >> data;
cin.ignore();
// again write inputted data into the file.
outfile << data << endl;
// close the opened file.
outfile.close();
// open a file in read mode.
ifstream infile;
infile.open("afile.dat");
cout << "Reading from the file" << endl;
infile >> data;
// write the data at the screen.
cout << data << endl;
// again read the data from the file and display it.
infile >> data;
cout << data << endl;
// close the opened file.
infile.close();
return 0;
When the above code is compiled and executed, it produces following sample
input and output:
$./a.out
Writing to the file
Enter your name: Zara
Enter your age: 9
Reading from the file
Zara
54: The following is the example of a function template that
returns the maximum of two values:
#include <iostream>
#include <string>
using namespace std;
template <typename T>
inline T const& Max (T const& a, T const& b)
{
return a < b ? b:a;
}
int main ()
{
int i = 39;
int j = 20;
cout << "Max(i, j): " << Max(i, j) << endl;
double f1 = 13.5;
double f2 = 20.7;
cout << "Max(f1, f2): " << Max(f1, f2) << endl;
string s1 = "Hello";
string s2 = "World";
cout << "Max(s1, s2): " << Max(s1, s2) << endl;
return 0;
}
If we compile and run above code, this would produce the following
result:
Max(i, j): 39
Max(f1, f2): 20.7
Max(s1, s2): World