0% found this document useful (0 votes)
9 views

Why To Learn C++

The document discusses the C++ programming language. It provides an overview of C++, including its history, uses, and basic syntax like variables and data types. It also discusses compiling C++ code and some common applications where C++ is used.

Uploaded by

Aswin Bharath
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Why To Learn C++

The document discusses the C++ programming language. It provides an overview of C++, including its history, uses, and basic syntax like variables and data types. It also discusses compiling C++ code and some common applications where C++ is used.

Uploaded by

Aswin Bharath
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 54

C++ is a middle-level programming language developed by Bjarne Stroustrup starting in 1979 at Bell Labs.

C++ runs on a variety of platforms,


such as Windows, Mac OS, and the various versions of UNIX. This C++ tutorial adopts a simple and practical approach to describe the concepts
of C++ for beginners to advanded software engineers.

Why to Learn C++


C++ is a MUST for students and working professionals to become a great Software Engineer. I will list down some of the key advantages of
learning C++:
 C++ is very close to hardware, so you get a chance to work at a low level which gives you lot of control in terms of memory
management, better performance and finally a robust software development.
 C++ programming gives you a clear understanding about Object Oriented Programming. You will understand low level
implementation of polymorphism when you will implement virtual tables and virtual table pointers, or dynamic type
identification.
 C++ is one of the every green programming languages and loved by millions of software developers. If you are a great C++
programmer then you will never sit without work and more importantly you will get highly paid for your work.
 C++ is the most widely used programming languages in application and system programming. So you can choose your area of
interest of software development.
 C++ really teaches you the difference between compiler, linker and loader, different data types, storage classes, variable types
their scopes etc.
There are 1000s of good reasons to learn C++ Programming. But one thing for sure, to learn any programming language, not only C++, you just
need to code, and code and finally code until you become expert.

Hello World using C++


Just to give you a little excitement about C++ programming, I'm going to give you a small conventional C++ Hello World program, You can
try it using Demo link
C++ is a super set of C programming with additional implementation of object-oriented concepts.
#include <iostream>
using namespace std;

// main() is where program execution begins.


int main() {
cout << "Hello World"; // prints Hello World
return 0;
}
There are many C++ compilers available which you can use to compile and run above mentioned program:
 Apple C++. Xcode
 Bloodshed Dev-C++
 Clang C++
 Cygwin (GNU C++)
 Mentor Graphics
 MINGW - "Minimalist GNU for Windows"
 GNU CC source
 IBM C++
 Intel C++
 Microsoft Visual C++
 Oracle C++
 HP C++
It is really impossible to give a complete list of all the available compilers. The C++ world is just too large and too much new is happening.

Applications of C++ Programming


As mentioned before, C++ is one of the most widely used programming languages. It has it's presence in almost every area of software
development. I'm going to list few of them here:
 Application Software Development - C++ programming has been used in developing almost all the major Operating Systems
like Windows, Mac OSX and Linux. Apart from the operating systems, the core part of many browsers like Mozilla Firefox and
Chrome have been written using C++. C++ also has been used in developing the most popular database system called MySQL.
 Programming Languages Development - C++ has been used extensively in developing new programming languages like C#,
Java, JavaScript, Perl, UNIX’s C Shell, PHP and Python, and Verilog etc.
 Computation Programming - C++ is the best friends of scientists because of fast speed and computational efficiencies.
 Games Development - C++ is extremely fast which allows programmers to do procedural programming for CPU intensive
functions and provides greater control over hardware, because of which it has been widely used in development of gaming
engines.
 Embedded System - C++ is being heavily used in developing Medical and Engineering Applications like softwares for MRI
machines, high-end CAD/CAM systems etc.
This list goes on, there are various areas where software developers are happily using C++ to provide great softwares. I highly recommend you
to learn C++ and contribute great softwares to the community.

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;
}
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;

// 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;
}
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;

// Global variable declaration:


int g = 20;

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 −

Data Type Initializer

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

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 −
#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
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.

Define C++ Objects


A class provides the blueprints for objects, so basically an object is created from a class. We declare objects of a class with exactly the same sort
of declaration that we declare variables of basic types. Following statements declare two objects of class Box −
Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box
Both of the objects Box1 and Box2 will have their own copy of data members.

Accessing the Data Members


The public data members of objects of a class can be accessed using the direct member access operator (.). Let us try the 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
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.

Classes and Objects in Detail


So far, you have got very basic idea about C++ Classes and Objects. There are further interesting concepts related to C++ Classes and Objects
which we will discuss in various sub-sections listed below −

Sr.No Concept & Description

1 Class Member Functions


A member function of a class is a function that has its definition or its prototype within the class
definition like any other variable.

2 Class Access Modifiers


A class member can be defined as public, private or protected. By default members would be
assumed as private.

3 Constructor & Destructor


A class constructor is a special function in a class that is called when a new object of the class is
created. A destructor is also a special function which is called when created object is deleted.
4 Copy Constructor
The copy constructor is a constructor which creates an object by initializing it with an object of the
same class, which has been created previously.

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.

8 Pointer to C++ Classes


A pointer to a class is done exactly the same way a pointer to a structure is. In fact a class is really
just a structure with functions in it.

9 Static Members of a Class


Both data members and function members of a class can be declared as static.

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 −
Live Demo

#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 −
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;
}

// 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;
}

private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a 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
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 −

:: .* . ?:
Operator Overloading Examples
Here are various operator overloading examples to help you in understanding the concept.

Sr.No Operators & Example

1 Unary Operators Overloading

2 Binary Operators Overloading

3 Relational Operators Overloading

4 Input/Output Operators Overloading

5 ++ and -- Operators Overloading

6 Assignment Operators Overloading

7 Function call () Operator Overloading

8 Subscripting [] Operator Overloading

9 Class Member Access Operator -> Overloading


Storage Classes in C++
A storage class defines the scope (visibility) and life-time of variables and/or functions within a C++ Program. These specifiers precede the type
that they modify. There are following storage classes, which can be used in a C++ Program

 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.

The register Storage Class


The register storage class is used to define local variables that should be stored in a register instead of RAM. This means that the variable has a
maximum size equal to the register size (usually one word) and can't have the unary '&' operator applied to it (as it does not have a memory
location).
{
register int miles;
}
The register should only be used for variables that require quick access such as counters. It should also be noted that defining 'register' does not
mean that the variable will be stored in a register. It means that it MIGHT be stored in a register depending on hardware and implementation
restrictions.
The static Storage Class
The static storage class instructs the compiler to keep a local variable in existence during the life-time of the program instead of creating and
destroying it each time it comes into and goes out of scope. Therefore, making local variables static allows them to maintain their values
between function calls.
The static modifier may also be applied to global variables. When this is done, it causes that variable's scope to be restricted to the file in which
it is declared.
In C++, when static is used on a class data member, it causes only one copy of that member to be shared by all objects of its class.

Live Demo

#include <iostream>

// Function declaration
void func(void);

static int count = 10; /* Global variable */

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>

extern int count;

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>

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
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 −

Access public protected private

Same class yes yes yes


Derived classes yes yes no

Outside classes yes no no

A derived class inherits all base class methods with the following exceptions −

 Constructors, destructors and copy constructors of the base class.


 Overloaded operators of the base class.
 The friend functions of the base class.
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.
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 −

Live Demo

#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
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 :" << width * height << endl;

return width * height;

};

class Rectangle: public Shape {


public:

Rectangle( int a = 0, int b = 0):Shape(a, b) { }

int area () {

cout << "Rectangle class area :" << width * height << 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 :" << (width * height)/2 << 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 :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>

using namespace std;

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 :" << width * height << endl;

return width * height;

};
class Rectangle: public Shape {

public:

Rectangle( int a = 0, int b = 0):Shape(a, b) { }

int area () {

cout << "Rectangle class area :" << width * height << 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 :" << (width * height)/2 << 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;

}
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.

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.

C++ Exception Handling


An exception is a problem that arises during the execution of a program. A C++ exception is a response to an exceptional circumstance that
arises while a program is running, such as an attempt to divide by zero.
Exceptions provide a way to transfer control from one part of a program to another. C++ exception handling is built upon three keywords: try,
catch, and throw.
 throw − A program throws an exception when a problem shows up. This is done using a throw keyword.
 catch − A program catches an exception with an exception handler at the place in a program where you want to handle the
problem. The catch keyword indicates the catching of an exception.
 try − A try block identifies a block of code for which particular exceptions will be activated. It's followed by one or more catch
blocks.
Assuming a block will raise an exception, a method catches an exception using a combination of the try and catch keywords. A try/catch block
is placed around the code that might generate an exception. Code within a try/catch block is referred to as protected code, and the syntax for
using try/catch as follows −
try {
// protected code
} catch( ExceptionName e1 ) {
// catch block
} catch( ExceptionName e2 ) {
// catch block
} catch( ExceptionName eN ) {
// catch block
}
You can list down multiple catch statements to catch different type of exceptions in case your try block raises more than one exception in
different situations.
Throwing Exceptions
Exceptions can be thrown anywhere within a code block using throw statement. The operand of the throw statement determines a type for the
exception and can be any expression and the type of the result of the expression determines the type of exception thrown.
Following is an example of throwing an exception when dividing by zero condition occurs −
double division(int a, int b) {
if( b == 0 ) {
throw "Division by zero condition!";
}
return (a/b);
}
Catching Exceptions
The catch block following the try block catches any exception. You can specify what type of exception you want to catch and this is determined
by the exception declaration that appears in parentheses following the keyword catch.
try {
// protected code
} catch( ExceptionName e ) {
// code to handle ExceptionName exception
}
Above code will catch an exception of ExceptionName type. If you want to specify that a catch block should handle any type of exception that
is thrown in a try block, you must put an ellipsis, ..., between the parentheses enclosing the exception declaration as follows −
try {
// protected code
} catch(...) {
// code to handle any exception
}
The following is an example, which throws a division by zero exception and we catch it in catch block.

Live Demo
#include <iostream>
using namespace std;

double division(int a, int b) {


if( b == 0 ) {
throw "Division by zero condition!";
}
return (a/b);
}

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 −

Sr.No Exception & Description


1
std::exception
An exception and parent class of all the standard C++ exceptions.

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;

struct MyException : public exception {


const char * what () const throw () {
return "C++ Exception";
}
};

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>

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
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>

using namespace std;

template <class T>


class Stack {
private:
vector<T> elems; // elements

public:
void push(T const&); // push element
void pop(); // pop element
T top() const; // return top element

bool empty() const { // return true if empty.


return elems.empty();
}
};

template <class T>


void Stack<T>::push (T const& elem) {
// append copy of passed element
elems.push_back(elem);
}

template <class T>


void Stack<T>::pop () {
if (elems.empty()) {
throw out_of_range("Stack<>::pop(): empty stack");
}

// remove last element


elems.pop_back();
}

template <class T>


T Stack<T>::top () const {
if (elems.empty()) {
throw out_of_range("Stack<>::top(): empty stack");
}

// return copy of last element


return elems.back();
}

int main() {
try {
Stack<int> intStack; // stack of ints
Stack<string> stringStack; // stack of strings

// manipulate int stack


intStack.push(7);
cout << intStack.top() <<endl;

// manipulate string stack


stringStack.push("hello");
cout << stringStack.top() << std::endl;
stringStack.pop();
stringStack.pop();
} catch (exception const& ex) {
cerr << "Exception: " << ex.what() <<endl;
return -1;
}
}
If we compile and run above code, this would produce the following result −
7
hello
Exception: Stack<>::pop(): empty stack

You might also like