C++ Cheat Sheet: Syntax
C++ Cheat Sheet: Syntax
C++ Cheat Sheet: Syntax
Syntax
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!";
return 0;
}
● Line 1: ‘#include <iostream>’ specifies the header file library, which helps you deal with
input and output objects like “cout.” Header files are used to add specific functionality to
C++ programs.
● Line 2: ‘using namespace std’ allows you to use names for objects and variables from
the standard library.
● Line 3: Blank line. C++ ignores the spaces present within the code.
● Line 4: ‘int main()’, which is a function. Any code within the curly brackets {} will be
executed.
● Line 5: cout is an object used along with the insertion operator (<<) to print the output
text.
● Line 6: return 0 is used to end the main function.
While writing code in C++, always make sure you end each line with a semicolon to specify the
end of the line. You must also add the closing bracket to end the main function; otherwise, you’ll
get errors while compiling the code.
Comments
In C++, the compiler ignores the text followed by the comments. C++ supports two different
types of comments:
● Built-in or primitive data types: Pre-defined data types that can be used directly,
including Integer, Character, Boolean, Floating Point, Double Floating Point, Valueless or
Void, and Wide Character.
● Derived data types: Derived from primitive data types: function, array, pointer, and
reference.
● User-defined data types: Defined by users: class, structure, union, enumeration, and
Typedef.
Variables
Variables store the data values. C++ supports various types of variables, such as int, double,
string, char, and float.
For example:
int num = 12; // Integer
string name = "Unity Buddy"; // String(text)
char ch = 'U'; //character
float fl = 5.99; // Floating point number
You can use alphabets, numbers, and the underscore for a variable name. However, variables
cannot start with numbers or the underscore ‘_’ character. Instead, they begin with letters
followed by numbers or the underscore ‘_’ character. Moreover, you cannot use a keyword for
the variable name.
Variables Scope
In C++, you can declare your variables within three parts of the program, also known as the
scope of the variables:
Local Variables
These variables are declared within a function or block of code. Their scope is only limited to
that function or block and cannot be accessed by any other statement outside that block.
For example:
#include <iostream>
using namespace std;
int main () {
// Local variable:
int a, b;
int c;
// initialization
a = 10;
b = 20;
c = a + b;
cout << c;
return 0;
}
Global Variables
Global variables are accessible to any function, method, or block of the program. Usually, it is
defined outside all the functions. The value of the global variable is the same throughout the
program.
For example:
#include <iostream>
using namespace std;
// Global variable:
int g;
int main () {
// Local variable:
int a, b;
// initialization
a = 10;
b = 20;
g = a + b;
cout << g;
return 0;
}
Literals
Literals in C++ are data that you can use to represent the fixed values. You can use them
directly within the code.
Integer literal
An integer literal is numeric and does not have any fractional or exponential part.
For example:
Floating-Point Literals
These are numeric literals that have either a fractional part or an exponent part.
Character Literal
These are single characters enclosed within a single quote.
For example:
Escape
Sequences Characters
\b Backspace
\f Form feed
\n Newline
\r Return
\t Horizontal tab
\v Vertical tab
\\ Backslash
Single quotation
\' mark
Double quotation
\" mark
\? Question mark
\0 Null Character
String Literal
This is a sequence of characters enclosed within double quotes.
For example:
For example:
Math Functions
C++ provides several functions that allow you to perform mathematical tasks. The following
table highlights all the basic math functions available in C++:
Function Description
abs(x) Returns the absolute value of x
acos(x) Returns the arccosine of x
asin(x) Returns the arcsine of x
expm1(x) Returns ex -1
fabs(x) Returns the absolute value of a floating x
fdim(x, y) Returns the positive difference between x and y
floor(x) Returns the value of x rounded down to its nearest integer
hypot(x, y) Returns sqrt(x2 +y2) without intermediate overflow or underflow
fma(x, y, z) Returns x*y+z without losing precision
fmax(x, y) Returns the highest value of a floating x and y
fmin(x, y) Returns the lowest value of a floating x and y
fmod(x, y) Returns the floating point remainder of x/y
pow(x, y) Returns the value of x to the power of y
sin(x) Returns the sine of x (x is in radians)
sinh(x) Returns the hyperbolic sine of a double value
tan(x) Returns the tangent of an angle
tanh(x) Returns the hyperbolic tangent of a double value
User Inputs
C++ supports “cout” and “cin” for displaying outputs and for taking inputs from users,
respectively. The cout uses the iteration operator (<<), and cin uses (>>).
For example:
Strings
A string is a collection or sequence of characters enclosed within double-quotes.
For example:
To use string within your code, you must include the string library using this code line:
#include <string>
C++ will then allow you to perform various functions to manipulate strings. The following table
describes the function names and their descriptions:
Function Description
int compare(const string& str) Compare two string objects
string& append(const string& Adds a new character at the end of another string object
str)
int find_first_not_of(string& str, Searches for the string for the first character that does not
int pos, int n ) match with any of the characters specified in the string
int find_last_of(string& str, int Searches for the string for the last character of a specified
pos, int n) sequence
int find_last_not_of(string& str, Searches for the last character that does not match with the
int pos) specified sequence
string& insert() Inserts a new character before the character indicated by the
position pos
int max_size() Finds the maximum length of the string
void push_back(char ch) Adds a new character ch at the end of the string
void shrink_to_fit() Reduces the capacity and makes it equal to the size of the
string
char* c_str() Returns pointer to an array containing a null terminated
sequence of characters
void reserve(inr len) Requests a change in capacity
allocator_type get_allocator(); Returns the allocated object associated with the string
Operators
C++ supports different types of operators to add logic to your code and perform operations on
variables and their respective values. Here are the C++ operator types:
Arithmetic Operators
You can perform common mathematical operations with arithmetic operators.
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
++ Increment ++x
-- Decrement --x
Assignment Operators
You can assign values to variables with assignment operators.
Comparison Operators
You can use these operators to compare two values to return a true or false value. It will return
true if both the values match, and false if they don’t match.
Logical Operators
These operators determine the logic between variables.
Decision-Making Statements
Decision-making statements in C++ decide the flow of program execution. Here, programmers
specify more than one condition. If a condition holds true the statements in that block are
executed. Otherwise, the statements from other blocks are executed instead.
● If statement
● if..else statement
● Switch statement
● Nested if statement
● Nested switch statement
● Ternary operator
If Statement
This is the most basic type of decision-making statement. It instructs the compiler to execute the
block of code only if the condition holds true.
Syntax:
if (expression)
{ //code}
Example:
#include <iostream>
using namespace std;
int main () {
int b = 10;
if( b < 20 ) {
cout << "b is less than 20;" << endl;
}
cout << "value of a is : " << b << endl;
return 0;
}
If..Else Statement
This is an extension of the ‘if’ statement. It instructs the compiler to execute the ‘if’ block only if
the specified condition is true. Otherwise, it executes the ‘else’ block.
Syntax:
if (expression)
{//code}
else
{//code}
Example:
#include <iostream>
using namespace std;
int main () {
int b = 10;
if( b < 20 ) {
cout << "b is less than 20;" << endl;
}
cout << "value of a is : " << b << endl;
return 0;
}
Switch Statement
When you need to execute conditions against various values, you can use switch statements.
Syntax:
switch(expression) {
case constant-expression :
statement(s);
break; //optional
case constant-expression :
statement(s);
break; //optional
default : //Optional
statement(s);
}
Example:
#include <iostream>
using namespace std;
int main () {
// local variable declaration:
char grade = 'D';
switch(grade) {
case 'A' :
cout << "Outstanding!" << endl;
break;
case 'B' :
case 'C' :
cout << "Well done" << endl;
break;
case 'D' :
cout << "Pass" << endl;
break;
case 'F' :
cout << "Try again" << endl;
break;
default :
cout << "Invalid grade" << endl;
}
cout << "Your grade is " << grade << endl;
return 0;
}
Nested If Statement
This is an “if” statement inside another “if” statement. You can use this type of statement when
you need to base a specific condition on the result of another condition.
Syntax:
if( boolean_expression 1) {
// Executes when the boolean expression 1 is true
if(boolean_expression 2) {
// Executes when the boolean expression 2 is true
}
}
Example:
#include <iostream>
using namespace std;
int main () {
// local variable declaration:
int x = 100;
int y = 200;
if( x == 100 ) {
if( y == 200 ) {
cout << "Value of x is 100 and y is 200" << endl;
}
}
cout << "Exact value of x is : " << x << endl;
cout << "Exact value of y is : " << y << endl;
return 0;
}
Syntax:
switch(ch1) {
case 'A':
cout << "This A is part of outer switch";
switch(ch2) {
case 'A':
cout << "This A is part of inner switch";
break;
case 'B': // ...
}
break;
case 'B': // ...
}
Example:
#include <iostream>
using namespace std;
int main () {
int x = 100;
int y = 200;
switch(x) {
case 100:
cout << "This is part of outer switch" << endl;
switch(y) {
case 200:
cout << "This is part of inner switch" << endl;
}
}
cout << "Exact value of x is : " << x << endl;
cout << "Exact value of y is : " << y << endl;
return 0;
}
Ternary Operator
First, expression Exp1 is evaluated. If it’s 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.
Loops
Loops are used to execute a particular set of commands for a specific number of time based on
the result of the evaluated condition. C++ includes the following loops
● While loop
● Do-while loop
● For loop
● Break statement
● Continue statement
While Loop
The loop will continue till the specified condition is true.
while (condition)
{code}
Do-While Loop
When the condition becomes false, the do-while loop stops executing. However, the only
difference between the while and do-while loop is that the do-while loop tests the condition after
executing the loop. Therefore, the loop gets executed at least once.
do
{
Code
}
while (condition)
For Loop
You can use the for loop to execute a block of code multiple times. This loop runs the block until
the condition specified in it holds false.
Break Statement
This is used to break the flow of the code so the remaining code isn’t executed. This brings you
out of the loop.
For example:
Continue Statement
This statement will break the flow and take you to the evaluation of the condition. Later, it starts
the code execution again.
For example:
Arrays
Arrays are derived data types that store multiple data items of similar types at contiguous
memory locations.
For example:
For this, you need to declare, define, and call that function. C++ has several built-in functions
that you can call directly within any program.
Defining a Function
The following is the syntax for defining a function in C++:
Where:
For example:
return result;
}
Calling a Function
You must call a function wherever you need it in your program.
For example:
#include <iostream>
using namespace std;
// function declaration
int max(int num1, int num2);
int main () {
int a = 100;
int b = 200;
int ret;
return 0;
}
Function Arguments
You can pass arguments in three ways:
● Call by value: Passes the actual value of an argument into the formal parameter
of the function. It will not make any change to the parameter inside the function
and does not effect on the argument.
● Call by pointer: You can copy an argument address into the formal parameter.
Here, the address accesses the actual argument used in the call. This means
that changes made to the parameter affect the argument.
● Call by reference: You can copy an argument reference into the formal
parameter. The reference accesses the actual argument used in the call. This
means that changes made to the parameter affect the argument.
Storage Classes
Storage classes define the visibility of the variables and functions. C++ supports various storage
classes, like auto, register, extern, static, and mutable.
Auto Storage Class
By default, C++ uses this storage class for all variables.
For example:
{
int var;
auto int var1;
}
You can only use the “auto” within functions for defining the local variables.
For example:
{
register int miles;
}
Global variables are static, which means their scope will be restricted to their declared file. If you
specify a class data member as static, it creates only one copy of that member that all objects of
its class will share.
For example:
#include <iostream>
// Function declaration
void func1(void);
static int count = 10; /* Global variable */
main() {
while(count--) {
func();
}
return 0;
}
// Function definition
void func1( void ) {
static int i = 5; // local static variable
i++;
std::cout << "i is " << i ;
std::cout << " and count is " << count << std::endl;
}
In case of multiple files where you define a global variable or function, also to be used in other
files, extern will provide a reference in another file of defined variable or function. You must use
the extern modifier when you have to share the same global variables or functions between two
or more files.
For example:
Program 1
#include <iostream>
int count ;
extern void write_extern();
main() {
count = 5;
write_extern();
}
STL Cheat Sheet
Creation
• Make an empty vector of integers.
• Make a 100-element vector of string, double pairs, each initialized to “height”, -1.
vector< pair< string, double > > pseq( 100, make_pair( string("height"), -1.0 ) );
vector< vector< int > > matrix2( 10, vector< int >( 20, 3 ) );
iseq1.size()
matrix2.size()
1
• Number of elements in the first row of a vector of vectors.
matrix2[ 0 ].size()
iseq2.front()
iseq2.back()
iseq1.begin()
• Return an iterator pointing to the imaginary position one past the end of the vector.
iseq1.end()
iseq2[ 5 ]
matrix2[ 7 ]
matrix2[ 7 ][ 3 ]
• Compute the value of an iterator pointing to the element at index 5 of the vector.
iseq1.begin() + 5
myPair.first
myPair.second
2
Insertion and Removal
• Add a integer to the end of a vector.
iseq1.push_back( 20 );
iseq1.pop_back();
iseq2.insert( pseq.begin() + 5, 99 );
• Append a new row of 100 elements (each set to zero) to the end of this vector of vectors.
• Insert a new row of 55 elements (each initialized to 75) at the start of this vector of vectors.
iseq2.erase( pseq.begin() );
pseq.erase( pseq.begin() + 7 );
iseq2.clear();
• Empty the last row of a vector of vectors, but don’t remove it.
matrix2.back().clear();
3
Supporting Algorithms
• Print out every element of a vector.
// Using iterators
for ( vector< int > :: iterator pos = iseq1.begin(); pos != iseq1.end(); pos++ )
cout << *pos << endl;
• Sort contents of vector of pairs, ordering by < for the first fields and using the second fields if first fields
are identical.
• Return an iterator pointing to the first occurrence of the value 5 in a vector. If not found, return the
given end iterator.
4
STL Cheat Sheet 2 – set, map
Creation
• Make an empty set of integers.
set<int> intSet1;
• Make a set of integers containing the given array of numbers.
int array[] = {10, 20, 30, 40};
set<int> intSet2(array, array + 4);
• Make an empty map from string to int.
map<string, int> siMap1;
• Make an empty map from C-string to int.
struct compareString {
bool operator()(const char *s1, const char *s2) const {
return strcmp(s1, s2) < 0;
}
}
1
Finding
• Find an item in a set (returns an iterator).
intSet1.find(3)
• See if an item is in a set.
if (intSet1.find(3) != intSet1.end()) ...
• Find an item in a map (returns an iterator).
siMap1.find("hello")
2
www.cppforschool.com
Structure
A structure is a collection of variable which can be same or different types. You
can refer to a structure as a single variable and to its parts as members of that
variable by using the dot (.) operator. The power of structures lies in the fact
that once defined, the structure name becomes a user-defined data type and
may be used the same way as other built-in data types, such as int, double,
char.
struct Student
{
int rollno, age;
char name[80];
float marks;
};
int main()
{
return 0;
}
Defining a structure
When dealing with the students in a school, many variables of different types
are needed. It may be necessary to keep track of name, age, Rollno, and
marks point for example.
struct Student
{
int rollno, age;
char name[80];
float marks;
};
Student is called the structure tag, and is your brand new data type, like int,
double or char.
int main()
{
// declare two variables of the new type
Student s1, s3;
………
………
return 0;
}
Alternate method of declaring variables of type struct:
struct Student
{
int rollno, age;
char name[80];
float marks;
} s1, s3;
s3 = s2;
struct Student
{
int rollno, age;
char name[80];
Day date_of_birth;
float marks;
};
s.date_of_birth.month = 11;
s.date_of_birth.date = 5;
s.date_of_birth.year = 1999;
typedef
It is used to define new data type for an existing data type. It provides and
alternative name for standard data type. It is used for self documenting the
code by allowing descriptive name for the standard data type.
for example:
It is user defined.
It works if you know in advance a finite list of values that a data type can
take.
The list cannot be input by the user or output on the screen.
Macros
Macros are built on the #define preprocessor. Normally a macro would look like:
#define square(x) x*x
Its arguments substituted for replacement text, when the macro is expanded.
www.cppforschool.com
Pointer
POINTER
A pointer is a variable that holds a memory address, usually the location of
another variable in memory.
Memory layout
int arr[]={4,7,11};
int *ptr = arr;
What is ptr + 1?
It means (address in ptr) + (1 * size of an int)
cout << *(ptr+1); // displays 7
cout << *(ptr+2); // displays 11
Array Access
Array notation arr[i] is equivalent to the pointer notation *(arr + i)
#include<iostream>
using namespace std;
int main()
{
int a=10,b=20;
swap(&a, &b);
cout<<a<<" "<<b;
return 0;
}
void swap(int *x, int *y)
{
int t;
t=*x;
*x=*y;
*y=t;
}
output:
20 10
Pointers to Constants and Constant Pointers
Pointers to Structures
We can create pointers to structure variables
Free store
Free store is a pool of unallocated heap memory given to a program that is used
by the program for dynamic allocation during execution.
To allocate array
double *dptr = new double[25];
Memory Leak
If the objects, that are allocated memory dynamically, are not deleted using
delete, the memory block remains occupied even at the end of the program.
Such memory blocks are known as orphaned memory blocks. These orphaned
memory blocks when increase in number, bring adverse effect on the system.
This situation is called memory leak
struct node
{
int data;
node* next;
}
www.cppforschool.com
Text file. It is a file that stores information in ASCII characters. In text files,
each line of text is terminated with a special character known as EOL (End of
Line) character or delimiter character. When this EOL character is read or
written, certain internal translations take place.
Binary file. It is a file that contains information in the same format as it is held
in memory. In binary files, no delimiters are used for a line and no translations
occur here.
Opening a file
OPENING FILE USING CONSTRUCTOR
ofstream outFile("sample.txt"); //output only
ifstream inFile(“sample.txt”); //input only
ofstream outFile;
outFile.open("sample.txt");
ifstream inFile;
inFile.open("sample.txt");
File mode parameter Meaning
ios::app Append to end of file
ios::ate go to end of file on opening
ios::binary file open in binary mode
ios::in open file for reading only
ios::out open file for writing only
ios::nocreate open fails if the file does not exist
ios::noreplace open fails if the file already exist
ios::trunc delete the contents of the file if it exist
All these flags can be combined using the bitwise operator OR (|). For example,
if we want to open the file example.bin in binary mode to add data we could do
it by the following call to member function open():
fstream file;
file.open ("example.bin", ios::out | ios::app | ios::binary);
Closing File
outFile.close();
inFile.close();
ofstream, like ostream, has a pointer known as the put pointer that points to
the location where the next element has to be written.
Finally, fstream, inherits both, the get and the put pointers, from iostream
(which is itself derived from both istream and ostream).
These internal stream pointers that point to the reading or writing locations
within a stream can be manipulated using the following member functions:
seekg(offset, refposition );
seekp(offset, refposition );
The parameter offset represents the number of bytes the file pointer is to be
moved from the location specified by the parameter refposition. The refposition
takes one of the following three constants defined in the ios class.
example:
file.seekg(-10, ios::cur);
www.cppforschool.com
#include <fstream>
using namespace std;
int main()
{
ofstream fout;
fout.open("out.txt");
fout.close();
return 0;
}
#include<fstream>
#include<iostream>
using namespace std;
int main()
{
ifstream fin;
fin.open("out.txt");
char ch;
while(!fin.eof())
{
fin.get(ch);
cout << ch;
}
fin.close();
return 0;
}
#include<fstream>
#include<iostream>
using namespace std;
int main()
{
ifstream fin;
fin.open("out.txt");
int count = 0;
char ch;
while(!fin.eof())
{
fin.get(ch);
count++;
}
fin.close();
return 0;
}
Program to count number of words
#include<fstream>
#include<iostream>
using namespace std;
int main()
{
ifstream fin;
fin.open("out.txt");
int count = 0;
char word[30];
while(!fin.eof())
{
fin >> word;
count++;
}
fin.close();
return 0;
}
#include<fstream>
#include<iostream>
using namespace std;
int main()
{
ifstream fin;
fin.open("out.txt");
int count = 0;
char str[80];
while(!fin.eof())
{
fin.getline(str,80);
count++;
}
#include<fstream>
using namespace std;
int main()
{
ifstream fin;
fin.open("out.txt");
ofstream fout;
fout.open("sample.txt");
char ch;
while(!fin.eof())
{
fin.get(ch);
fout << ch;
}
fin.close();
return 0;
}
#include<iostream>
#include<fstream>
#include<cstdio>
using namespace std;
class Student
{
int admno;
char name[50];
public:
void setData()
{
cout << "\nEnter admission no. ";
cin >> admno;
cout << "Enter name of student ";
cin.getline(name,50);
}
void showData()
{
cout << "\nAdmission no. : " << admno;
cout << "\nStudent Name : " << name;
}
int retAdmno()
{
return admno;
}
};
/*
* function to write in a binary file.
*/
void write_record()
{
ofstream outFile;
outFile.open("student.dat", ios::binary | ios::app);
Student obj;
obj.setData();
outFile.write((char*)&obj, sizeof(obj));
outFile.close();
}
/*
* function to display records of file
*/
void display()
{
ifstream inFile;
inFile.open("student.dat", ios::binary);
Student obj;
while(inFile.read((char*)&obj, sizeof(obj)))
{
obj.showData();
}
inFile.close();
}
/*
* function to search and display from binary file
*/
void search(int n)
{
ifstream inFile;
inFile.open("student.dat", ios::binary);
Student obj;
while(inFile.read((char*)&obj, sizeof(obj)))
{
if(obj.retAdmno() == n)
{
obj.showData();
}
}
inFile.close();
}
/*
* function to delete a record
*/
void delete_record(int n)
{
Student obj;
ifstream inFile;
inFile.open("student.dat", ios::binary);
ofstream outFile;
outFile.open("temp.dat", ios::out | ios::binary);
while(inFile.read((char*)&obj, sizeof(obj)))
{
if(obj.retAdmno() != n)
{
outFile.write((char*)&obj, sizeof(obj));
}
}
inFile.close();
outFile.close();
remove("student.dat");
rename("temp.dat", "student.dat");
}
/*
* function to modify a record
*/
void modify_record(int n)
{
fstream file;
file.open("student.dat",ios::in | ios::out);
Student obj;
while(file.read((char*)&obj,sizeof(obj)))
{
if(obj.retAdmno() == n)
{
cout << "\nEnter the new details of student";
obj.setData();
file.write((char*)&obj, sizeof(obj));
}
}
file.close();
}
int main()
{
//Store 4 records in file
for(int i = 1; i <= 4; i++)
write_record();
//Search record
cout << "\nSearch result";
search(100);
//Delete record
delete_record(100);
cout << "\nRecord Deleted";
//Modify record
cout << "\nModify Record 101 ";
modify_record(101);
return 0;
}
www.cppforschool.com
OOP Concepts
There are two common programming methods: procedural programming and
object-oriented programming (OOP). So far you have been creating procedural
programs.
Procedural Programming
In a procedural program data is typically stored in a collection of variables and
there is a set of functions that perform operations on the data. The data and the
functions are separate entities. Usually the variables are passed to the functions
that perform the desired operations. As you might imagine, the focus of
procedural programming is on creating the functions, or procedures, that
operate on the program’s data. Procedural programming works well. However,
as programs become larger and more complex, the separation of a program’s
data and the code that operates on the data can lead to problems.
An object is an entity that combines both data and procedures in a single unit.
An object’s data items, also referred to as its attributes, are stored in member
variables. The procedures that an object performs are called its member
functions. This wrapping of an object’s data and procedures together is called
encapsulation.
Not only objects encapsulate associated data and procedures, they also permit
data hiding. Data hiding refers to an object’s ability to hide its data from code
outside the object. Only the object’s member functions can directly access and
make changes to the object’s data.
Where class_name is a valid identifier for the class. The body of the declaration
can contain members, that can be either data or function declarations, The
members of a class are classified into three categories: private, public, and
protected. private, protected, and public are reserved words and are called
member access specifiers. These specifiers modify the access rights that the
members following them acquire.
private members of a class are accessible only from within other members of
the same class. You cannot access it outside of the class.
protected members are accessible from members of their same class and also
from members of their derived classes.
Finally, public members are accessible from anywhere where the object is
visible.
By default, all members of a class declared with the class keyword have private
access for all its members. Therefore, any member that is declared before one
other class specifier automatically has private access.
Object Declaration
Once a class is defined, you can declare objects of that type. The syntax for
declaring a object is the same as that for declaring any other variable. The
following statements declare two objects of type circle:
Circle c1, c2;
#include <iostream>
using namespace std;
int main()
{
Circle c1; //define object of class circle
c1.setRadius(2.5); //call member function to initialize radius
cout << c1.getArea(); //display area of circle object
return 0;
}
www.cppforschool.com
Constructor
It is a member function having same name as it’s class and which is used to
initialize the objects of that class type with a legal initial value. Constructor is
automatically called when object is created.
Types of Constructor
Default Constructor-: A constructor that accepts no parameters is known as
default constructor. If no constructor is defined then the compiler supplies a
default constructor.
Circle :: Circle()
{
radius = 0;
}
int main()
{
Circle c1; //default constructor invoked
Circle c2(2.5); //parmeterized constructor invoked
Circle c3(c2); //copy constructor invoked
cout << c1.getArea()<<endl;
cout << c2.getArea()<<endl;
cout << c3.getArea()<<endl;
return 0;
}
#include<iostream>
#include<iomanip>
using namespace std;
class Time
{
private :
int hour;
int minute;
int second;
public :
//constructor with default value 0
Time(int h = 0, int m = 0, int s = 0);
//setter function
void setTime(int h, int m, int s);
//print description of object in hh:mm:ss
void print();
//compare two time object
bool equals(Time);
};
int main()
{
Time t1(10, 50, 59);
t1.print(); // 10:50:59
Time t2; //object created with default value
t2.print(); // 00:00:00
t2.setTime(6, 39, 9); //set the new time in object
t2.print(); // 06:39:09
if(t1.equals(t2))
cout << "Two objects are equals\n";
else
cout << "Two objects are not equals\n";
return 0;
}
Output :
10:50:59
00:00:00
06:39:09
Two objects are not equals
Let's us discuss our Time class and add some new concepts of programming
Constructors with Default Arguments
Constant Function
In some cases, you will need that the member function should not change any
private member variables of the calling object. You can do this by adding const
to the end of the function declaration (prototype) and in the function definition.
class Time
{
...
...
//print description of object in hh:mm:ss
void print() const;
...
...
};
....
....
void Time :: print() const
{
cout << setw(2) << setfill('0') << hour << ":"
<< setw(2) << setfill('0') << minute << ":"
<< setw(2) << setfill('0') << second << "\n";
}
....
Constant Parameters
......
This means that equals() receives a copy of object t2 with name otherTime.
If a function needs to store or change data in an object’s member variables, the
object must be passed to it by reference.
Header File
Class declarations are stored in a separate file. A file that contains a class
declaration is called header file. The name of the class is usually the same as
the name of the class, with a .h extension. For example, the Time class would
be declared in the file Time .h.
#ifndef TIME_H
#define TIME_H
class Time
{
private :
int hour;
int minute;
int second;
public :
//with default value
Time(const int h = 0, const int m = 0, const int s = 0);
// setter function
void setTime(const int h, const int m, const int s);
// Print a description of object in " hh:mm:ss"
void print() const;
//compare two time object
bool equals(const Time&);
};
#endif
Implementation File
The member function definitions for a class are stored in a separate .cpp file,
which is called the class implementation file. The file usually has the same name
as the class, with the .cpp extension. For example the Time class member
functions would be defined in the file Time.cpp.
#include <iostream>
#include <iomanip>
#include "Time.h"
using namespace std;
Client code, is the one that includes the main function. This file should be stored
by the name main.cpp
#include <iostream>
using namespace std;
#include "Time.h"
int main()
{
Time t1(10, 50, 59);
t1.print(); // 10:50:59
Time t2;
t2.print(); // 06:39:09
t2.setTime(6, 39, 9);
t2.print(); // 06:39:09
if(t1.equals(t2))
cout << "Two objects are equal\n";
else
cout << "Two objects are not equal\n";
return 0;
}
2. The clients of the class know what member functions the class provides, how
to call them and what return types to expect.
3. The clients do not know how the class's member functions are implemented.
www.cppforschool.com
In some situations it may be desirable that one or more common data fields
should exist, which are accessible to all objects of the class. In C++, a static
member is shared by all objects of the class.
#include <iostream>
using namespace std;
class Circle
{
private:
double radius; // Radius of a circle
public:
static int count;
// Constructor definition
Circle(double r = 1.0)
{
radius = r;
// Increase every time object is created
count++;
}
double getArea()
{
return 3.14 * radius * radius;
}
};
// Initialize static member of class Circle
int Circle::count = 0;
int main()
{
Circle c1(3.3); // Declare object c1
Circle c2(4.5); // Declare object c2
return 0;
}
Output:
Total objects: 2
The static functions can access only the static data of a class. Similarly, static
functions cannot call non-static functions of the class.
Functions which are static and which are declared in the public section of a class
can be called without specifying an object of the class. This is illustrated in the
following code fragment:
#include <iostream>
using namespace std;
class Circle
{
private:
static int count;
double radius; // Radius of a circle
public:
// Constructor definition
Circle(double r = 1.0)
{
radius = r;
// Increase every time object is created
count++;
}
double getArea()
{
return 3.14 * radius * radius;
}
static int getCount()
{
return count;
}
};
int main()
{
Circle c1(3.3); // Declare object c1
Circle c2(4.5); // Declare object c2
return 0;
}
Output:
Total objects: 2
www.cppforschool.com
Friend Functions
As we have seen in the previous sections, private and protected data or function
members are normally only accessible by the code which is part of same class.
However, situations may arise in which it is desirable to allow the explicit access
to private members of class to other functions.
#include <iostream>
using namespace std;
class Rectangle
{
private :
int length;
int width;
public:
int getArea()
{
return length * width ;
}
Output :
Expense 300
The getCost function is a friend of Rectangle. From within that function we have
been able to access the members length and width, which are private members.
Friend Classes
One class member function can access the private and protected members of
other class. We do it by declaring a class as friend of other class. This is
illustrated in the following code fragment:
#include <iostream>
using namespace std;
class CostCalculator;
class Rectangle
{
private :
int length;
int width;
public:
void setData(int len, int wid)
{
length = len;
width = wid;
}
int getArea()
{
return length * width ;
}
class CostCalculator
{
public :
double getCost (Rectangle rect)
{
double cost;
cost = rect.length * rect.width * 5;
return cost;
}
};
int main ()
{
Rectangle floor;
floor.setData(20,3);
CostCalculator calc;
cout << "Expense " << calc.getCost(floor) << endl;
return 0;
}
Output :
Expense 300
In the following code fragment, we will overload binary + operator for Complex
number class object.
#include <iostream>
using namespace std;
class Complex
{
private :
double real;
double imag;
public:
Complex () {};
Complex (double, double);
Complex operator + (Complex);
void print();
};
void Complex::print()
{
cout << real << " + i" << imag << endl;
}
int main ()
{
Complex c1 (3.1, 1.5);
Complex c2 (1.2, 2.2);
Complex c3;
c1.print();
c2.print();
c3.print();
return 0;
}
Output :
3.1 + i1.5
1.2 + i2.2
4.3 + i3.7
That is similiar to
c3 = c1.operator+(c2);
www.cppforschool.com
Inheritance
The mechanism that allows us to extend the definition of a class without making
any physical changes to the existing class is inheritance.
Inheritance lets you create new classes from existing class. Any new class that
you create from an existing class is called derived class; existing class is called
base class.
The inheritance relationship enables a derived class to inherit features from its
base class. Furthermore, the derived class can add new features of its own.
Therefore, rather than create completely new classes from scratch, you can
take advantage of inheritance and reduce software complexity.
Forms of Inheritance
Where derived_class is the name of the derived class and base_class is the
name of the class on which it is based. The member Access Specifier may be
public, protected or private. This access specifier describes the access level for
the members that are inherited from the base class.
Member How Members of the Base Class Appear in the
Access Derived Class
Specifier
class Shape
{
protected:
float width, height;
public:
void set_data (float a, float b)
{
width = a;
height = b;
}
};
output :
15
5
set_data () and area() are public members of derived class and can be accessed
from outside class i.e. from main()
www.cppforschool.com
This is done by specifying the arguments to the selected base class constructor
in the definition of the derived class constructor.
class Rectangle
{
private :
float length;
float width;
public:
Rectangle ()
{
length = 0;
width = 0;
}
float area()
{
return length * width ;
}
};
float volume()
{
return area() * height;
}
};
int main ()
{
Box bx;
Box cx(4,8,5);
cout << bx.volume() << endl;
cout << cx.volume() << endl;
return 0;
}
output :
0
160
A derived class can override a member function of its base class by defining a
derived class member function with the same name and parameter list.
It is often useful for a derived class to define its own version of a member
function inherited from its base class. This may be done to specialize the
member function to the needs of the derived class. When this happens, the
base class member function is said to be overridden by the derived class.
class mother
{
public:
void display ()
{
cout << "mother: display function\n";
}
};
int main ()
{
daughter rita;
rita.display();
return 0;
}
output:
daughter: display function
class A
{
.....
.....
};
class Shape
{
protected:
double width, height;
public:
void set_data (double a, double b)
{
width = a;
height = b;
}
};
int main ()
{
Shape *sPtr; //declare pointer variables of type Shape
Rectangle Rect; //create the object rect of type Rectangle
sPtr = &Rect; //make sPtr point to the object rect.
return 0;
}
Notice that even though rectPtr is pointing to rect (object of type Rectangle), when
the program executes, the statement sets length and width of rectangle. If you tried
to access area function of class Rectangle with sPtr it will give you compiler error.
sPtr -> area()
is a compiler error !
It means base class pointer can not access the additional member function of
its derived class. If we want to do this we need to type cast the base class pointer.
The type cast informs the compiler that sPtr is actually pointing to a Rectangle object
derived from the Shape base class. In general, a pointer to a base class that
actually points to a derived class object must first be appropriately cast
before the additional features of the derived class can be used.
class Shape
{
protected:
double width, height;
public:
void set_data (double a, double b)
{
width = a;
height = b;
}
virtual double area()
{return 0;}
};
int main ()
{
Shape *sPtr;
Rectangle Rect;
sPtr = &Rect;
return 0;
}
Output :
15
A member of a class that can be redefined in its derived classes is known as a virtual
member. In order to declare a member of a class as virtual, we must precede its
declaration with the keyword virtual. The member function area() has been declared
as virtual in the base class because it is later redefined in each
derived class. The advantage of having virtual function is that we are able to
access area function of derived class by pointer variable of base class.
A class derived from an abstract class inherits all functions in the base class, and will
itself be an abstract class unless it overrides all the abstract functions it inherits. The
usefulness of abstract classes lies in the fact that they define an interface that will
then have to be supported by objects of all classes derived from it.
#include <iostream>
using namespace std;
class Shape
{
protected:
double width, height;
public:
void set_data (double a, double b)
{
width = a;
height = b;
}
virtual double area() = 0;
};
int main ()
{
Shape *sPtr;
Rectangle Rect;
sPtr = &Rect;
Triangle Tri;
sPtr = &Tri;
Output :
Area of Rectangle is 15
Area of Triangle is 12
C++ EXCEPTION HANDLING
http://www.tutorialspoint.com/cplusplus/cpp_exceptions_handling.htm Copyright © tutorialspoint.com
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 looks like the following:
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 statements. The operand of
the throw statements 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.
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.
#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:
Exception Description
std::exception An exception and parent class of all the standard C++ exceptions.
std::out_of_range This can be thrown by the at method from for example a std::vector and
std::bitset<>::operator[].
std::range_error This is occured when you try to store a value which is out of range.
#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
}
}
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.
Loading [MathJax]/jax/output/HTML-CSS/jax.js