Why To Learn C++
Why To Learn C++
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.
#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;
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;
}
Lvalues and Rvalues
There are two kinds of expressions in C++ −
lvalue − Expressions that refer to a memory location is called "lvalue" expression. An lvalue may appear as either the left-hand or
right-hand side of an assignment.
rvalue − The term rvalue refers to a data value that is stored at some address in memory. An rvalue is an expression that cannot
have a value assigned to it which means an rvalue may appear on the right- but not left-hand side of an assignment.
Variables are lvalues and so may appear on the left-hand side of an assignment. Numeric literals are rvalues and so may not be assigned and can
not appear on the left-hand side. Following is a valid statement −
int g = 20;
But the following is not a valid statement and would generate compile-time error −
10 = 20;
Variable Scope in C++
A scope is a region of the program and broadly speaking there are three places, where variables can be declared −
Inside a function or a block which is called local variables,
In the definition of function parameters which is called formal parameters.
Outside of all functions which is called global variables.
We will learn what is a function and it's parameter in subsequent chapters. Here let us explain what are local and global variables.
Local Variables
Variables that are declared inside a function or block are local variables. They can be used only by statements that are inside that function or
block of code. Local variables are not known to functions outside their own. Following is the example using local variables −
Live Demo
#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;
}
Global Variables
Global variables are defined outside of all the functions, usually on top of the program. The global variables will hold their value throughout the
life-time of your program.
A global variable can be accessed by any function. That is, a global variable is available for use throughout your entire program after its
declaration. Following is the example using global and local variables −
#include <iostream>
using namespace std;
int main () {
// Local variable declaration:
int a, b;
// actual initialization
a = 10;
b = 20;
g = a + b;
cout << g;
return 0;
}
A program can have same name for local and global variables but value of local variable inside a function will take preference. For example −
#include <iostream>
using namespace std;
int main () {
// Local variable declaration:
int g = 10;
cout << g;
return 0;
}
When the above code is compiled and executed, it produces the following result −
10
Initializing Local and Global Variables
When a local variable is defined, it is not initialized by the system, you must initialize it yourself. Global variables are initialized automatically
by the system when you define them as follows −
int 0
char '\0'
float 0
double 0
pointer NULL
It is a good programming practice to initialize variables properly, otherwise sometimes program would produce unexpected result.
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
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;
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 −
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.
return 0;
}
When the above code is compiled and executed, it produces the following result −
Total value is :300
Total value is :120
C++ Classes and Objects
The main purpose of C++ programming is to add object orientation to the C programming language and classes are the central feature of C++
that supports object-oriented programming and are often called user-defined types.
A class is used to specify the form of an object and it combines data representation and methods for manipulating that data into one neat
package. The data and functions within a class are called members of the class.
C++ Class Definitions
When you define a class, you define a blueprint for a data type. 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.
A class definition starts with the keyword class followed by the class name; and the class body, enclosed by a pair of curly braces. A class
definition must be followed either by a semicolon or a list of declarations. For example, we defined the Box data type using the keyword class as
follows −
class Box {
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
The keyword public determines the access attributes of the members of the class that follows it. A public member can be accessed from outside
the class anywhere within the scope of the class object. You can also specify the members of a class as private or protected which we will
discuss in a sub-section.
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
It is important to note that private and protected members can not be accessed directly using direct member access operator (.). We will learn
how private and protected members can be accessed.
5 Friend Functions
A friend function is permitted full access to private and protected members of a class.
6 Inline Functions
With an inline function, the compiler tries to expand the code in the body of the function in place of a
call to the function.
7 this Pointer
Every object has a special pointer this which points to the object itself.
#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);
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 −
Live Demo
#include <iostream>
using namespace std;
class 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;
}
private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
// 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;
// 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
Overloadable/Non-overloadableOperators
Following is the list of operators which can be overloaded −
+ - * / % ^
& | ~ ! , =
+= -= /= %= ^= &=
|= *= <<= >>= [] ()
:: .* . ?:
Operator Overloading Examples
Here are various operator overloading examples to help you in understanding the concept.
auto
register
static
extern
mutable
The auto Storage Class
The auto storage class is the default storage class for all local variables.
{
int mount;
auto int month;
}
The example above defines two variables with the same storage class, auto can only be used within functions, i.e., local variables.
Live Demo
#include <iostream>
// Function declaration
void func(void);
main() {
while(count--) {
func();
}
return 0;
}
// Function definition
void func( void ) {
static int i = 5; // local static variable
i++;
std::cout << "i is " << i ;
std::cout << " and count is " << count << std::endl;
}
When the above code is compiled and executed, it produces the following result −
i is 6 and count is 9
i is 7 and count is 8
i is 8 and count is 7
i is 9 and count is 6
i is 10 and count is 5
i is 11 and count is 4
i is 12 and count is 3
i is 13 and count is 2
i is 14 and count is 1
i is 15 and count is 0
The extern Storage Class
The extern storage class is used to give a reference of a global variable that is visible to ALL the program files. When you use 'extern' the
variable cannot be initialized as all it does is point the variable name at a storage location that has been previously defined.
When you have multiple files and you define a global variable or function, which will be used in other files also, then extern will be used in
another file to give reference of defined variable or function. Just for understanding extern is used to declare a global variable or function in
another file.
The extern modifier is most commonly used when there are two or more files sharing the same global variables or functions as explained below.
First File: main.cpp
#include <iostream>
int count ;
extern void write_extern();
main() {
count = 5;
write_extern();
}
Second File: support.cpp
#include <iostream>
void write_extern(void) {
std::cout << "Count is " << count << std::endl;
}
Here, extern keyword is being used to declare count in another file. Now compile these two files as follows −
$g++ main.cpp support.cpp -o write
This will produce write executable program, try to execute write and check the result as follows −
$./write
5
The mutable Storage Class
The mutable specifier applies only to class objects, which are discussed later in this tutorial. It allows a member of an object to override const
member function. That is, a mutable member can be modified by a const member function.
C++ 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.
Consider a base class Shape and its derived class Rectangle as follows −
Live Demo
#include <iostream>
// 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);
return 0;
}
When the above code is compiled and executed, it produces the following result −
Total area: 35
Access Control and Inheritance
A derived class can access all the non-private members of its base class. Thus base-class members that should not be accessible to the member
functions of derived classes should be declared private in the base class.
We can summarize the different access types according to - who can access them in the following way −
A derived class inherits all base class methods with the following exceptions −
Live Demo
#include <iostream>
protected:
int width;
int height;
};
// 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();
return 0;
}
When the above code is compiled and executed, it produces the following result −
Total area: 35
Total paint cost: $2450
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>
class Shape {
protected:
public:
width = a;
height = b;
int area() {
cout << "Parent class area :" << width * height << endl;
};
int area () {
cout << "Rectangle class area :" << width * height << endl;
};
public:
int area () {
cout << "Triangle class area :" << (width * height)/2 << endl;
};
int main() {
Shape *shape;
Rectangle rec(10,7);
Triangle tri(10,5);
shape = &rec;
shape->area();
shape = &tri;
shape->area();
return 0;
}
When the above code is compiled and executed, it produces the following result −
Parent class area :70
Parent class area :50
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 −
#include <iostream>
class Shape {
protected:
public:
width = a;
height = b;
cout << "Parent class area :" << width * height << endl;
};
class Rectangle: public Shape {
public:
int area () {
cout << "Rectangle class area :" << width * height << endl;
};
public:
int area () {
cout << "Triangle class area :" << (width * height)/2 << endl;
};
Shape *shape;
Rectangle rec(10,7);
Triangle tri(10,5);
shape = &rec;
shape->area();
shape = &tri;
shape->area();
return 0;
}
After this slight modification, when the previous example code is compiled and executed, it produces the following result −
Rectangle class area :70
Triangle class area :25
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.
public:
Shape(int a = 0, int b = 0) {
width = a;
height = b;
}
Live Demo
#include <iostream>
using namespace std;
int main () {
int x = 50;
int y = 0;
double z = 0;
try {
z = division(x, y);
cout << z << endl;
} catch (const char* msg) {
cerr << msg << endl;
}
return 0;
}
Because we are raising an exception of type const char*, so while catching this exception, we have to use const char* in catch block. If we
compile and run above code, this would produce the following result −
Division by zero condition!
C++ Standard Exceptions
C++ provides a list of standard exceptions defined in <exception> which we can use in our programs. These are arranged in a parent-child class
hierarchy shown below −
Here is the small description of each exception mentioned in the above hierarchy −
2
std::bad_alloc
This can be thrown by new.
3
std::bad_cast
This can be thrown by dynamic_cast.
4
std::bad_exception
This is useful device to handle unexpected exceptions in a C++ program.
5
std::bad_typeid
This can be thrown by typeid.
6
std::logic_error
An exception that theoretically can be detected by reading the code.
7
std::domain_error
This is an exception thrown when a mathematically invalid domain is used.
8
std::invalid_argument
This is thrown due to invalid arguments.
9
std::length_error
This is thrown when a too big std::string is created.
10
std::out_of_range
This can be thrown by the 'at' method, for example a std::vector and std::bitset<>::operator[]().
11
std::runtime_error
An exception that theoretically cannot be detected by reading the code.
12
std::overflow_error
This is thrown if a mathematical overflow occurs.
13
std::range_error
This is occurred when you try to store a value which is out of range.
14
std::underflow_error
This is thrown if a mathematical underflow occurs.
Define New Exceptions
You can define your own exceptions by inheriting and overriding exception class functionality. Following is the example, which shows how you
can use std::exception class to implement your own exception in standard way −
Live Demo
#include <iostream>
#include <exception>
using namespace std;
int main() {
try {
throw MyException();
} catch(MyException& e) {
std::cout << "MyException caught" << std::endl;
std::cout << e.what() << std::endl;
} catch(std::exception& e) {
//Other errors
}
}
This would produce the following result −
MyException caught
C++ Exception
Here, what() is a public method provided by exception class and it has been overridden by all the child exception classes. This returns the cause
of an exception.
C++ Templates
Templates are the foundation of generic programming, which involves writing code in a way that is independent of any particular type.
A template is a blueprint or formula for creating a generic class or a function. The library containers like iterators and algorithms are examples of
generic programming and have been developed using template concept.
There is a single definition of each container, such as vector, but we can define many different kinds of vectors for example, vector
<int> or vector <string>.
You can use templates to define functions as well as classes, let us see how they work −
Function Template
The general form of a template function definition is shown here −
template <class type> ret-type func-name(parameter list) {
// body of function
}
Here, type is a placeholder name for a data type used by the function. This name can be used within the function definition.
The following is the example of a function template that returns the maximum of two values −
Live Demo
#include <iostream>
#include <string>
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
Class Template
Just as we can define function templates, we can also define class templates. The general form of a generic class declaration is shown here −
template <class type> class class-name {
.
.
.
}
Here, type is the placeholder type name, which will be specified when a class is instantiated. You can define more than one generic data type by
using a comma-separated list.
Following is the example to define class Stack<> and implement generic methods to push and pop the elements from the stack −
Live Demo
#include <iostream>
#include <vector>
#include <cstdlib>
#include <string>
#include <stdexcept>
public:
void push(T const&); // push element
void pop(); // pop element
T top() const; // return top element
int main() {
try {
Stack<int> intStack; // stack of ints
Stack<string> stringStack; // stack of strings