[go: up one dir, main page]

0% found this document useful (0 votes)
166 views42 pages

C++ Overloading (Operator and Function)

C++ allows function and operator overloading which allows multiple definitions of the same function or operator name as long as the parameter types are different. When a function or operator is called, overload resolution determines the most appropriate definition to use based on the argument types. Functions can be overloaded based on number and type of parameters but not return type alone. Operators can be overloaded as member or non-member functions with special operator names. Some operators like ::, ., and ?: cannot be overloaded in C++.

Uploaded by

Kiptoo Nickson
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
166 views42 pages

C++ Overloading (Operator and Function)

C++ allows function and operator overloading which allows multiple definitions of the same function or operator name as long as the parameter types are different. When a function or operator is called, overload resolution determines the most appropriate definition to use based on the argument types. Functions can be overloaded based on number and type of parameters but not return type alone. Operators can be overloaded as member or non-member functions with special operator names. Some operators like ::, ., and ?: cannot be overloaded in C++.

Uploaded by

Kiptoo Nickson
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 42

C++ Overloading (Operator and Function)

C++ allows you to specify more than one definition for a function name or
an operator in the same scope, which is called function overloading and operator
overloading respectively.
An overloaded declaration is a declaration that is declared with the same name as a
previously declared declaration in the same scope, except that both declarations have
different arguments and obviously different definition (implementation).
When you call an overloaded function or operator, the compiler determines the most
appropriate definition to use, by comparing the argument types you have used to call
the function or operator with the parameter types specified in the definitions. The
process of selecting the most appropriate overloaded function or operator is
called overload resolution.

Function Overloading in C++


You can have multiple definitions for the same function name in the same scope. The
definition of the function must differ from each other by the types and/or the number of
arguments in the argument list. You cannot overload function declarations that differ
only by return type.
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;
}

When the above code is compiled and executed, it produces the following result −
Printing int: 5
Printing float: 500.263
Printing character: Hello C++

Operators Overloading in C++


You can redefine or overload most of the built-in operators available in C++. Thus, a
programmer can use operators with user-defined types as well.
Overloaded operators are functions with special names: the keyword "operator"
followed by the symbol for the operator being defined. Like any other function, an
overloaded operator has a return type and a parameter list.
Box operator+(const Box&);
declares the addition operator that can be used to add two Box objects and returns
final Box object. Most overloaded operators may be defined as ordinary non-member
functions or as class member functions. In case we define above function as non-
member function of a class then we would have to pass two arguments for each
operand as follows −
Box operator+(const Box&, const Box&);
Following is the example to show the concept of operator over loading using a member
function. Here an object is passed as an argument whose properties will be accessed
using this object, the object which will call this operator can be accessed
using this operator as explained below −

Example: Operator overloading in C++


Programming
1. #include <iostream>
2. using namespace std;
3.
4. class Test
5. {
6. private:
7. int count;
8.
9. public:
10. Test(): count(5){}
11.
12. void operator ++()
13. {
14. count = count+1;
15. }
16. void Display() { cout<<"Count: "<<count; }
17. };
18.
19. int main()
20. {
21. Test t;
22. // this calls "function void operator ++()" function
23. ++t;
24. t.Display();
25. return 0;
26. }

Overloadable/Non-overloadableOperators
Following is the list of operators which can be overloaded −

+ - * / % ^

& | ~ ! , =

< > <= >= ++ --

<< >> == != && ||

+= -= /= %= ^= &=

|= *= <<= >>= [] ()

-> ->* new new [] delete delete []

Following is the list of operators, which can not be overloaded −

:: .* . ?:
Things to remember
1. Operator overloading allows you to redefine the way operator works for user-
defined types only (objects, structures). It cannot be used for built-in types (int, float,
char etc.).
2. Two operators = and & are already overloaded by default in C++. For example:
To copy objects of same class, you can directly use = operator. You do not need to
create an operator function.
3. Operator overloading cannot change the precedence and associatively of
operators. However, if you want to change the order of evaluation, parenthesis should
be used.
4. There are 4 operators that cannot be overloaded in C++. They are :: (scope
resolution), . (member selection), .* (member selection through pointer to function)
and ?: (ternary operator).

INHERITANCE

One of the most important concepts in object-oriented programming is that of


inheritance. Inheritance allows us to define a class in terms of another class, which
makes it easier to create and maintain an application. This also provides an opportunity
to reuse the code functionality and fast implementation time.
When creating a class, instead of writing completely new data members and member
functions, the programmer can designate that the new class should inherit the
members of an existing class. This existing class is called the base class, and the new
class is referred to as the derived class.
The idea of inheritance implements the is a relationship. For example, mammal IS-A
animal, dog IS-A mammal hence dog IS-A animal as well and so on.

Base and Derived Classes


A class can be derived from more than one classes, which means it can inherit data
and functions from multiple base classes. To define a derived class, we use a class
derivation list to specify the base class(es). A class derivation list names one or more
base classes and has the form −
class derived-class: access-specifier base-class
Where access-specifier is one of public, protected, or private, and base-class is the
name of a previously defined class. If the access-specifier is not used, then it is private
by default.
DATA ACCESS MODIFIERS
Data hiding is one of the important features of Object Oriented Programming which
allows preventing the functions of a program to access directly the internal
representation of a class type. The access restriction to the class members is specified
by the labeled access modifiers: public, private, and protected sections within the class
body.
The default access for members and classes is private.
class Base {
public:
   // public members go here
protected:

   // protected members go here


private:
   // private members go here
};
A public member is accessible from anywhere outside the class but within a program.
You can set and get the value of public variables without any member.
A private member variable or function cannot be accessed, or even viewed from outside
the class. Only the class and friend functions can access private members.
A protected member variable or function is very similar to a private member but it
provided one additional benefit that they can be accessed in child classes which are
called derived classes.

Accessibility in Public Inheritance


private protected public
Accessibility variables variables variables

Accessible from own class? yes yes yes

Accessible from derived


class? no yes yes

Accessible from 2nd derived


class? no yes yes
Accessibility in Protected Inheritance
private protected
Accessibility variables variables public variables

Accessible from own


class? yes yes yes

yes
Accessible from derived (inherited as protected
class? no yes variables)

Accessible from 2nd


derived class? no yes yes

Accessibility in Private Inheritance


private
Accessibility variables protected variables public variables

Accessible from own


class? yes yes yes

yes yes
Accessible from derived (inherited as private (inherited as private
class? no variables) variables)

Accessible from 2nd


derived class? no no no

Type of Inheritance
When deriving a class from a base class, the base class may be inherited
through public, protected or private inheritance. The type of inheritance is specified
by the access-specifier as explained above.
We hardly use protected or private inheritance, but public inheritance is commonly
used. While using different type of inheritance, following rules are applied −
 Public Inheritance − When deriving a class from a public base class, public members of
the base class become public members of the derived class and protected members of
the base class become protected members of the derived class. A base
class's private members are never accessible directly from a derived class, but can be
accessed through calls to the public and protected members of the base class.
 Protected Inheritance − When deriving from a protected base
class, public and protected members of the base class become protected members of
the derived class.
 Private Inheritance − When deriving from a private base
class, public and protected members of the base class become private members of the
derived class.
TYPES
Single, multiple, multilevel, hierarchical and hybrid inheritance

Multiple Inheritance
A C++ class can inherit members from more than one class and here is the extended
syntax −
class derived-class: access baseA, access baseB....
Where access is one of public, protected, or private and would be given for every
base class and they will be separated by comma as shown above. 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

OBJECT ORIENTED PROGRAMMING USING C++


The prime purpose of C++ programming was to add object orientation to the C
programming language, which is in itself one of the most powerful programming
languages.
The core of the pure object-oriented programming is to create an object, in code, that
has certain properties and methods. While designing C++ modules, we try to see
whole world in the form of objects. For example a car is an object which has certain
properties such as color, number of doors, and the like. It also has certain methods
such as accelerate, brake, and so on.
There are a few principle concepts that form the foundation of object-oriented
programming −

Object
This is the basic unit of object oriented programming. That is both data and function
that operate on data are bundled as a unit called as object.

Class
When you define a class, you define a blueprint for an object. This doesn't actually
define any data, but it does define what the class name means, that is, what an object
of the class will consist of and what operations can be performed on such an object.

Abstraction
Data abstraction refers to, providing only essential information to the outside world and
hiding their background details, i.e., to represent the needed information in program
without presenting the details.
For example, a database system hides certain details of how data is stored and
created and maintained. Similar way, C++ classes provides different methods to the
outside world without giving internal detail about those methods and data.

Encapsulation
Encapsulation is placing the data and the functions that work on that data in the same
place. While working with procedural languages, it is not always clear which functions
work on which variables but object-oriented programming provides you framework to
place the data and the relevant functions together in the same object.

Inheritance
One of the most useful aspects of object-oriented programming is code reusability. As
the name suggests Inheritance is the process of forming a new class from an existing
class that is from the existing class called as base class, new class is formed called as
derived class.
This is a very important concept of object-oriented programming since this feature
helps to reduce the code size.

Polymorphism
The ability to use an operator or function in different ways in other words giving
different meaning or functions to the operators or functions is called polymorphism.
Poly refers to many. That is a single function or an operator functioning in many ways
different upon the usage is called polymorphism.

Overloading
The concept of overloading is also a branch of polymorphism. When the exiting
operator or function is made to operate on new data type, it is said to be overloaded.

Compile and Execute C++ Program


Let's look at how to save the file, compile and run the program. Please follow the steps
given below −
 Open a text editor and add the code as above.
 Save the file as: hello.cpp
 Open a command prompt and go to the directory where you saved the file.
 Type 'g++ hello.cpp' and press enter to compile your code. If there are no errors in your
code the command prompt will take you to the next line and would generate a.out
executable file.
 Now, type 'a.out' to run your program.
 You will be able to see ' Hello World ' printed on the window.
 Semicolons and Blocks in C++
 In C++, the semicolon is a statement terminator. That is, each individual
statement must be ended with a semicolon. It indicates the end of one logical
entity.
 For example, following are three different statements −
 x = y;
 y = y + 1;

 add(x, y);
 A block is a set of logically connected statements that are surrounded by
opening and closing braces. For example −
 {
 cout << "Hello World"; // prints Hello World
 return 0;
 }
 C++ does not recognize the end of the line as a terminator. For this reason, it
does not matter where you put a statement in a line. For example −
 x = y;
 y = y + 1;
 add(x, y);
 is the same as
 x = y; y = y + 1; add(x, y);
 C++ Identifiers
 A C++ identifier is a name used to identify a variable, function, class, module, or
any other user-defined item. An identifier starts with a letter A to Z or a to z or an
underscore (_) followed by zero or more letters, underscores, and digits (0 to 9).
 C++ does not allow punctuation characters such as @, $, and % within
identifiers. C++ is a case-sensitive programming language.
Thus, Manpower and manpower are two different identifiers in C++.
 Here are some examples of acceptable identifiers −
 mohd zara abc move_name a_123
 myname50 _temp j a23b9 retVal
 C++ Keywords
 The following list shows the reserved words in C++. These reserved words may
not be used as constant or variable or any other identifier names.

Asm else new this

Auto enum operator throw

Bool explicit private true

Break export protected try

Case extern public typedef

Catch false register typeid

Char float reinterpret_cast typename

Class for return union

Const friend short unsigned

const_cast goto signed using


Continue if sizeof virtual

Default inline static void

Delete int static_cast volatile

Do long struct wchar_t

Double mutable switch while

dynamic_cast namespace template  

Comments in C++
Program comments are explanatory statements that you can include in the C++ code.
These comments help anyone reading the source code. All programming languages
allow for some form of comments.
C++ supports single-line and multi-line comments. All characters available inside any
comment are ignored by C++ compiler.
C++ comments start with /* and end with */. For example −
/* This is a comment */

/* C++ comments can also


* span multiple lines
*/
A comment can also start with //, extending to the end of the line. For example −
Live Demo
#include <iostream>
using namespace std;

main() {
cout << "Hello World"; // prints Hello World

return 0;
}
When the above code is compiled, it will ignore // prints Hello World and final
executable will produce the following result −
Hello World
Within a /* and */ comment, // characters have no special meaning. Within a //
comment, /* and */ have no special meaning. Thus, you can "nest" one kind of
comment within the other kind. For example −
/* Comment out printing of Hello World:

cout << "Hello World"; // prints Hello World

*/

C++ Data Types


While writing program in any language, you need to use various variables to store
various information. Variables are nothing but reserved memory locations to store
values. This means that when you create a variable you reserve some space in
memory.
You may like to store information of various data types like character, wide character,
integer, floating point, double floating point, boolean etc. Based on the data type of a
variable, the operating system allocates memory and decides what can be stored in the
reserved memory.

Primitive Built-in Types


C++ offers the programmer a rich assortment of built-in as well as user defined data
types. Following table lists down seven basic C++ data types −

Type Keyword

Boolean bool

Character char

Integer int

Floating point float

Double floating point double


Valueless void

Wide character wchar_t

Several of the basic types can be modified using one or more of these type modifiers −

 signed
 unsigned
 short
 long
The following table shows the variable type, how much memory it takes to store the
value in memory, and what is maximum and minimum value which can be stored in
such type of variables.

Type Typical Bit Width Typical Range

Char 1byte -127 to 127 or 0 to 255

unsigned char 1byte 0 to 255

signed char 1byte -127 to 127

Int 4bytes -2147483648 to 2147483647

unsigned int 4bytes 0 to 4294967295

signed int 4bytes -2147483648 to 2147483647

short int 2bytes -32768 to 32767

unsigned short int Range 0 to 65,535

signed short int Range -32768 to 32767


long int 4bytes -2,147,483,648 to 2,147,483,647

signed long int 4bytes same as long int

unsigned long int 4bytes 0 to 4,294,967,295

Float 4bytes +/- 3.4e +/- 38 (~7 digits)

Double 8bytes +/- 1.7e +/- 308 (~15 digits)

long double 8bytes +/- 1.7e +/- 308 (~15 digits)

wchar_t 2 or 4 bytes 1 wide character

The size of variables might be different from those shown in the above table,
depending on the compiler and the computer you are using.
Following is the example, which will produce correct size of various data types on your
computer.
Live Demo
#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;
}

This example uses endl, which inserts a new-line character after every line and <<
operator is being used to pass multiple values out to the screen. We are also
using sizeof() operator to get size of various data types.
When the above code is compiled and executed, it produces the following result which
can vary from machine to machine −
Size of char : 1
Size of int : 4
Size of short int : 2
Size of long int : 4
Size of float : 4
Size of double : 8
Size of wchar_t : 4

typedef Declarations
You can create a new name for an existing type using typedef. Following is the simple
syntax to define a new type using typedef −
typedef type newname;
For example, the following tells the compiler that feet is another name for int −
typedef int feet;
Now, the following declaration is perfectly legal and creates an integer variable called
distance −
feet distance;

Enumerated Types
An enumerated type declares an optional type name and a set of zero or more
identifiers that can be used as values of the type. Each enumerator is a constant
whose type is the enumeration.
Creating an enumeration requires the use of the keyword enum. The general form of
an enumeration type is −
enum enum-name { list of names } var-list;
Here, the enum-name is the enumeration's type name. The list of names is comma
separated.
For example, the following code defines an enumeration of colors called colors and the
variable c of type color. Finally, c is assigned the value "blue".
enum color { red, green, blue } c;
c = blue;
By default, the value of the first name is 0, the second name has the value 1, and the
third has the value 2, and so on. But you can give a name, a specific value by adding
an initializer. For example, in the following enumeration, green will have the value 5.
enum color { red, green = 5, blue };
Here, blue will have a value of 6 because each name will be one greater than the one
that precedes it.
C++ Variable Types
A variable provides us with named storage that our programs can manipulate. Each
variable in C++ has a specific type, which determines the size and layout of the
variable's memory; the range of values that can be stored within that memory; and the
set of operations that can be applied to the variable.
The name of a variable can be composed of letters, digits, and the underscore
character. It must begin with either a letter or an underscore. Upper and lowercase
letters are distinct because C++ is case-sensitive −
There are following basic types of variable in C++ as explained in last chapter −

Sr.No Type & Description

1
bool
Stores either value true or false.

2
char
Typically a single octet (one byte). This is an integer type.

3
int
The most natural size of integer for the machine.

4
float
A single-precision floating point value.

5
double
A double-precision floating point value.

6
void
Represents the absence of type.

7
wchar_t
A wide character type.
C++ also allows to define various other types of variables, which we will cover in
subsequent chapters like Enumeration, Pointer, Array, Reference, Data
structures, and Classes.
Following section will cover how to define, declare and use various types of variables.

Variable Definition in C++


A variable definition tells the compiler where and how much storage to create for the
variable. A variable definition specifies a data type, and contains a list of one or more
variables of that type as follows −
type variable_list;
Here, type must be a valid C++ data type including char, w_char, int, float, double,
bool or any user-defined object, etc., and variable_list may consist of one or more
identifier names separated by commas. Some valid declarations are shown here −
int i, j, k;
char c, ch;
float f, salary;
double d;
The line int i, j, k; both declares and defines the variables i, j and k; which instructs the
compiler to create variables named i, j and k of type int.
Variables can be initialized (assigned an initial value) in their declaration. The initializer
consists of an equal sign followed by a constant expression as follows −
type variable_name = value;
Some examples are −
extern int d = 3, f = 5; // declaration of d and f.
int d = 3, f = 5; // definition and initializing d and f.
byte z = 22; // definition and initializes z.
char x = 'x'; // the variable x has the value 'x'.
For definition without an initializer: variables with static storage duration are implicitly
initialized with NULL (all bytes have the value 0); the initial value of all other variables
is undefined.

Variable Declaration in C++


A variable declaration provides assurance to the compiler that there is one variable
existing with the given type and name so that compiler proceed for further compilation
without needing complete detail about the variable. A variable declaration has its
meaning at the time of compilation only, compiler needs actual variable definition at the
time of linking of the program.
A variable declaration is useful when you are using multiple files and you define your
variable in one of the files which will be available at the time of linking of the program.
You will use extern keyword to declare a variable at any place. Though you can
declare a variable multiple times in your C++ program, but it can be defined only once
in a file, a function or a block of code.

Example

Try the following example where a variable has been declared at the top, but it has
been defined inside the main function −
Live Demo

#include <iostream>
using namespace std;

// Variable declaration:
extern int a, b;
extern int c;
extern float f;

int main () {
// Variable definition:
int a, b;
int c;
float f;

// actual initialization
a = 10;
b = 20;
c = a + b;

cout << c << endl ;

f = 70.0/3.0;
cout << f << endl ;

return 0;
}

When the above code is compiled and executed, it produces the following result −
30
23.3333
Same concept applies on function declaration where you provide a function name at
the time of its declaration and its actual definition can be given anywhere else. For
example −
// function declaration
int func();
int main() {
// function call
int i = func();
}

// function definition
int func() {
return 0;
}

Operators in C++
An operator is a symbol that tells the compiler to perform specific mathematical or
logical manipulations. C++ is rich in built-in operators and provide the following types of
operators −

 Arithmetic Operators
 Relational Operators
 Logical Operators
 Bitwise Operators
 Assignment Operators
 Misc Operators
This chapter will examine the arithmetic, relational, logical, bitwise, assignment and
other operators one by one.

Arithmetic Operators
There are following arithmetic operators supported by C++ language −
Assume variable A holds 10 and variable B holds 20, then −
Show Examples

Operato Description Example


r

+ Adds two operands A + B will give 30

- Subtracts second operand from the first A - B will give -10

* Multiplies both operands A * B will give 200

/ Divides numerator by de-numerator B / A will give 2

% Modulus Operator and remainder of after an B % A will give 0


integer division

++ Increment operator, increases integer value A++ will give 11


by one

-- Decrement operator, decreases integer A-- will give 9


value by one

Relational Operators
There are following relational operators supported by C++ language
Assume variable A holds 10 and variable B holds 20, then −
Show Examples

Operato Description Example


r

== Checks if the values of two operands are (A == B) is not true.


equal or not, if yes then condition becomes
true.

!= Checks if the values of two operands are (A != B) is true.


equal or not, if values are not equal then
condition becomes true.

> Checks if the value of left operand is greater (A > B) is not true.
than the value of right operand, if yes then
condition becomes true.

< Checks if the value of left operand is less (A < B) is true.


than the value of right operand, if yes then
condition becomes true.

>= Checks if the value of left operand is greater (A >= B) is not true.
than or equal to the value of right operand,
if yes then condition becomes true.
<= Checks if the value of left operand is less (A <= B) is true.
than or equal to the value of right operand,
if yes then condition becomes true.

Logical Operators
There are following logical operators supported by C++ language.
Assume variable A holds 1 and variable B holds 0, then −
Show Examples

Operato Description Example


r

&& Called Logical AND operator. If both the (A && B) is false.


operands are non-zero, then condition
becomes true.

|| Called Logical OR Operator. If any of the (A || B) is true.


two operands is non-zero, then condition
becomes true.

! Called Logical NOT Operator. Use to !(A && B) is true.


reverses the logical state of its operand. If a
condition is true, then Logical NOT operator
will make false.

Bitwise Operators
Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &, |,
and ^ are as follows −

p q p&q p|q p^q

0 0 0 0 0

0 1 0 1 1
1 1 1 1 0

1 0 0 1 1

Assume if A = 60; and B = 13; now in binary format they will be as follows −
A = 0011 1100
B = 0000 1101
-----------------
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A  = 1100 0011
The Bitwise operators supported by C++ language are listed in the following table.
Assume variable A holds 60 and variable B holds 13, then −
Show Examples

Operato Description Example


r

& Binary AND Operator copies a bit to the


(A & B) will give 12 which is 0000 1100
result if it exists in both operands.

| Binary OR Operator copies a bit if it exists (A | B) will give 61 which is 0011 1101
in either operand.

^ Binary XOR Operator copies the bit if it is


(A ^ B) will give 49 which is 0011 0001
set in one operand but not both.

~ Binary Ones Complement Operator is unary (~A ) will give -61 which is 1100 0011 in 2's
and has the effect of 'flipping' bits. complement form due to a signed binary
number.

<< Binary Left Shift Operator. The left


operands value is moved left by the number A << 2 will give 240 which is 1111 0000
of bits specified by the right operand.
>> Binary Right Shift Operator. The left
operands value is moved right by the
A >> 2 will give 15 which is 0000 1111
number of bits specified by the right
operand.

Assignment Operators
There are following assignment operators supported by C++ language −
Show Examples

Operato Description Example


r

= Simple assignment operator, Assigns values C = A + B will assign value of A + B into


from right side operands to left side operand. C

+= Add AND assignment operator, It adds right


operand to the left operand and assign the C += A is equivalent to C = C + A
result to left operand.

-= Subtract AND assignment operator, It subtracts


right operand from the left operand and assign C -= A is equivalent to C = C - A
the result to left operand.

*= Multiply AND assignment operator, It multiplies


right operand with the left operand and assign C *= A is equivalent to C = C * A
the result to left operand.

/= Divide AND assignment operator, It divides left


operand with the right operand and assign the C /= A is equivalent to C = C / A
result to left operand.

%= Modulus AND assignment operator, It takes


modulus using two operands and assign the C %= A is equivalent to C = C % A
result to left operand.

<<= Left shift AND assignment operator. C <<= 2 is same as C = C << 2


>>= Right shift AND assignment operator. C >>= 2 is same as C = C >> 2

&= Bitwise AND assignment operator. C &= 2 is same as C = C & 2

^= Bitwise exclusive OR and assignment operator. C ^= 2 is same as C = C ^ 2

|= Bitwise inclusive OR and assignment operator. C |= 2 is same as C = C | 2

Misc Operators
The following table lists some other operators that C++ supports.

Sr.No Operator & Description

1
sizeof
sizeof operator returns the size of a variable. For example, sizeof(a), where ‘a’ is integer, and
will return 4.

2
Condition ? X : Y
Conditional operator (?). If Condition is true then it returns value of X otherwise returns value
of Y.

3
,
Comma operator causes a sequence of operations to be performed. The value of the entire
comma expression is the value of the last expression of the comma-separated list.

4
. (dot) and -> (arrow)
Member operators are used to reference individual members of classes, structures, and
unions.

5
Cast
Casting operators convert one data type to another. For example, int(2.2000) would return 2.

6
&
Pointer operator & returns the address of a variable. For example &a; will give actual address
of the variable.

7
*
Pointer operator * is pointer to a variable. For example *var; will pointer to a variable var.

Operators Precedence in C++


Operator precedence determines the grouping of terms in an expression. This affects
how an expression is evaluated. Certain operators have higher precedence than
others; for example, the multiplication operator has higher precedence than the
addition operator −
For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher
precedence than +, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with
the lowest appear at the bottom. Within an expression, higher precedence operators
will be evaluated first.
Show Examples

Category  Operator  Associativity 

Postfix  () [] -> . ++ - -   Left to right 

Unary  + - ! ~ ++ - - (type)* & sizeof  Right to left 

Multiplicative   * / %  Left to right 

Additive   + -  Left to right 

Shift   << >>  Left to right 

Relational   < <= > >=  Left to right 

Equality   == !=  Left to right 


Bitwise AND  &  Left to right 

Bitwise XOR  ^  Left to right 

Bitwise OR  |  Left to right 

Logical AND  &&  Left to right 

Logical OR  ||  Left to right 

Conditional  ?:  Right to left 

Assignment  = += -= *= /= %=>>= <<= &= ^= |=  Right to left 

Comma  ,  Left to right

C++ decision making statements


Decision making structures require that the programmer specify one or more conditions
to be evaluated or tested by the program, along with a statement or statements to be
executed if the condition is determined to be true, and optionally, other statements to
be executed if the condition is determined to be false.
Following is the general form of a typical decision making structure found in most of the
programming languages −
C++ programming language provides following types of decision making statements.

Sr.No Statement & Description

1 if statement

An ‘if’ statement consists of a boolean expression followed by one or more statements.

2 if...else statement
An ‘if’ statement can be followed by an optional ‘else’ statement, which executes when the
boolean expression is false.

3 switch statement
A ‘switch’ statement allows a variable to be tested for equality against a list of values.

4 nested if statements
You can use one ‘if’ or ‘else if’ statement inside another ‘if’ or ‘else if’ statement(s).

5 nested switch statements


You can use one ‘switch’ statement inside another ‘switch’ statement(s).

The ? : Operator
We have covered conditional operator “? :” in previous chapter which can be used to
replace if...else statements. It has the following general form −
Exp1 ? Exp2 : Exp3;
Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon.
The value of a ‘?’ expression is determined like this: Exp1 is evaluated. If it is true, then
Exp2 is evaluated and becomes the value of the entire ‘?’ expression. If Exp1 is false,
then Exp3 is evaluated and its value becomes the value of the expression.

C++ Loop Types


There may be a situation, when you need to execute a block of code several number of
times. In general, statements are executed sequentially: The first statement in a
function is executed first, followed by the second, and so on.
Programming languages provide various control structures that allow for more
complicated execution paths.
A loop statement allows us to execute a statement or group of statements multiple
times and following is the general from of a loop statement in most of the programming
languages −

C++ programming language provides the following type of loops to handle looping
requirements.

Sr.No Loop Type & Description


1 while loop

Repeats a statement or group of statements while a given condition is true. It tests the
condition before executing the loop body.

2 for loop
Execute a sequence of statements multiple times and abbreviates the code that manages the
loop variable.

3 do...while loop
Like a ‘while’ statement, except that it tests the condition at the end of the loop body.

4 nested loops
You can use one or more loop inside any another ‘while’, ‘for’ or ‘do..while’ loop.

Loop Control Statements


Loop control statements change execution from its normal sequence. When execution
leaves a scope, all automatic objects that were created in that scope are destroyed.
C++ supports the following control statements.

Sr.No Control Statement & Description

1 break statement

Terminates the loop or switch statement and transfers execution to the statement


immediately following the loop or switch.

2 continue statement
Causes the loop to skip the remainder of its body and immediately retest its condition prior to
reiterating.

3 goto statement
Transfers control to the labeled statement. Though it is not advised to use goto statement in
your program.

The Infinite Loop


A loop becomes infinite loop if a condition never becomes false. The for loop is
traditionally used for this purpose. Since none of the three expressions that form the
‘for’ loop are required, you can make an endless loop by leaving the conditional
expression empty.
#include <iostream>
using namespace std;

int main () {
for( ; ; ) {
printf("This loop will run forever.\n");
}

return 0;
}

When the conditional expression is absent, it is assumed to be true. You may have an
initialization and increment expression, but C++ programmers more commonly use the
‘for (;;)’ construct to signify an infinite loop.

C++ Functions
A function is a group of statements that together perform a task. Every C++ program
has at least one function, which is main(), and all the most trivial programs can define
additional functions.
You can divide up your code into separate functions. How you divide up your code
among different functions is up to you, but logically the division usually is such that
each function performs a specific task.
A function declaration tells the compiler about a function's name, return type, and
parameters. A function definition provides the actual body of the function.
The C++ standard library provides numerous built-in functions that your program can
call. For example, function strcat() to concatenate two strings, function memcpy() to
copy one memory location to another location and many more functions.
A function is known with various names like a method or a sub-routine or a procedure
etc.

Defining a Function
The general form of a C++ function definition is as follows −
return_type function_name( parameter list ) {
body of the function
}
A C++ function definition consists of a function header and a function body. Here are
all the parts of a function −
 Return Type − A function may return a value. The return_type is the data type of the value
the function returns. Some functions perform the desired operations without returning a
value. In this case, the return_type is the keyword void.
 Function Name − This is the actual name of the function. The function name and the
parameter list together constitute the function signature.
 Parameters − A parameter is like a placeholder. When a function is invoked, you pass a
value to the parameter. This value is referred to as actual parameter or argument. The
parameter list refers to the type, order, and number of the parameters of a function.
Parameters are optional; that is, a function may contain no parameters.
 Function Body − The function body contains a collection of statements that define what the
function does.

Example
Following is the source code for a function called max(). This function takes two
parameters num1 and num2 and return the biggest of both −
// 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;
}

Function Declarations
A function declaration tells the compiler about a function name and how to call the
function. The actual body of the function can be defined separately.
A function declaration has the following parts −
return_type function_name( parameter list );
For the above defined function max(), following is the function declaration −
int max(int num1, int num2);
Parameter names are not important in function declaration only their type is required,
so following is also valid declaration −
int max(int, int);
Function declaration is required when you define a function in one source file and you
call that function in another file. In such case, you should declare the function at the top
of the file calling the function.

Calling a Function
While creating a C++ function, you give a definition of what the function has to do. To
use a function, you will have to call or invoke that function.
When a program calls a function, program control is transferred to the called function.
A called function performs defined task and when it’s return statement is executed or
when its function-ending closing brace is reached, it returns program control back to
the main program.
To call a function, you simply need to pass the required parameters along with function
name, and if function returns a value, then you can store returned value. For example

Live Demo
#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;
}

I kept max() function along with main() function and compiled the source code. While
running final executable, it would produce the following result −
Max value is : 200

Function Arguments
If a function is to use arguments, it must declare variables that accept the values of the
arguments. These variables are called the formal parameters of the function.
The formal parameters behave like other local variables inside the function and are
created upon entry into the function and destroyed upon exit.
While calling a function, there are two ways that arguments can be passed to a
function −

Sr.No Call Type & Description

1 Call by Value

This method copies the actual value of an argument into the formal parameter of the function.
In this case, changes made to the parameter inside the function have no effect on the
argument.

2 Call by Pointer
This method copies the address of an argument into the formal parameter. Inside the
function, the address is used to access the actual argument used in the call. This means that
changes made to the parameter affect the argument.

3 Call by Reference
This method copies the reference of an argument into the formal parameter. Inside the
function, the reference is used to access the actual argument used in the call. This means
that changes made to the parameter affect the argument.

By default, C++ uses call by value to pass arguments. In general, this means that
code within a function cannot alter the arguments used to call the function and above
mentioned example while calling max() function used the same method.

Default Values for Parameters


When you define a function, you can specify a default value for each of the last
parameters. This value will be used if the corresponding argument is left blank when
calling to the function.
This is done by using the assignment operator and assigning values for the arguments
in the function definition. If a value for that parameter is not passed when the function
is called, the default given value is used, but if a value is specified, this default value is
ignored and the passed value is used instead. Consider the following example −
Live Demo
#include <iostream>
using namespace std;

int sum(int a, int b = 20) {


int result;
result = a + b;

return (result);
}
int main () {
// local variable declaration:
int a = 100;
int b = 200;
int result;

// calling a function to add the values.


result = sum(a, b);
cout << "Total value is :" << result << endl;

// calling a function again as follows.


result = sum(a);
cout << "Total value is :" << result << endl;

return 0;
}

When the above code is compiled and executed, it produces the following result −
Total value is :300
Total value is :120
B bn

C++ Class Constructor and Destructor


The Class Constructor
A class constructor is a special member function of a class that is executed whenever
we create new objects of that class.
A constructor will have exact same name as the class and it does not have any return
type at all, not even void. Constructors can be very useful for setting initial values for
certain member variables.
Following example explains the concept of constructor −
Live Demo

#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

Parameterized Constructor
A default constructor does not have any parameter, but if you need, a constructor can
have parameters. This helps you to assign initial value to an object at the time of its
creation as shown in the following example −
Live Demo
#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

Using Initialization Lists to Initialize Fields


In case of parameterized constructor, you can use following syntax to initialize the
fields −
Line::Line( double len): length(len) {
cout << "Object is being created, length = " << len << endl;
}
Above syntax is equal to the following syntax −
Line::Line( double len) {
cout << "Object is being created, length = " << len << endl;
length = len;
}
If for a class C, you have multiple fields X, Y, Z, etc., to be initialized, then use can use
same syntax and separate the fields by comma as follows −
C::C( double a, double b, double c): X(a), Y(b), Z(c) {
....
}

The Class Destructor


A destructor is a special member function of a class that is executed whenever an
object of it's class goes out of scope or whenever the delete expression is applied to a
pointer to the object of that class.
A destructor will have exact same name as the class prefixed with a tilde (~) and it can
neither return a value nor can it take any parameters. Destructor can be very useful for
releasing resources before coming out of the program like closing files, releasing
memories etc.
Following example explains the concept of destructor −
Live Demo

#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

Polymorphism in C++
The word polymorphism means having many forms. Typically, polymorphism occurs
when there is a hierarchy of classes and they are related by inheritance.
C++ polymorphism means that a call to a member function will cause a different
function to be executed depending on the type of object that invokes the function.
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 << "Triangle 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 :
The reason for the incorrect output is that the call of the function area() is being set
once by the compiler as the version defined in the base class. This is called static
resolution of the function call, or static linkage - the function call is fixed before the
program is executed. This is also sometimes called early binding because the area()
function is set during the compilation of the program.
But now, let's make a slight modification in our program and precede the declaration of
area() in the Shape class with 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
This time, the compiler looks at the contents of the pointer instead of it's type. Hence,
since addresses of objects of tri and rec classes are stored in *shape the respective
area() function is called.
As you can see, each of the child classes has a separate implementation for the
function area(). This is how polymorphism is generally used. You have different
classes with a function of the same name, and even the same parameters, but with
different implementations.

Virtual Function
A virtual function is a function in a base class that is declared using the
keyword virtual. Defining in a base class a virtual function, with another version in a
derived class, signals to the compiler that we don't want static linkage for this function.
What we do want is the selection of the function to be called at any given point in the
program to be based on the kind of object for which it is called. This sort of operation is
referred to as dynamic linkage, or late binding.
Pure Virtual Functions
It is possible that you want to include a virtual function in a base class so that it may be
redefined in a derived class to suit the objects of that class, but that there is no
meaningful definition you could give for the function in the base class.
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.

You might also like