C++ Programming Code Examples
C++ > Data Structures and Algorithm Analysis in C++ Code Examples
IntCell class interface
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/* IntCell class interface */
#ifndef IntCell_H_
#define IntCell_H_
/**
* A class for simulating an integer memory cell.
*/
class IntCell
{
public:
explicit IntCell( int initialValue = 0 );
int read( ) const;
void write( int x );
private:
int storedValue;
};
#endif
#define Directive in C++
In the C++ Programming Language, the #define directive allows the definition of macros within your source code. These macro definitions allow constant values to be declared for use throughout your code. Macro definitions are not variables and cannot be changed by your program code like variables. You generally use this syntax when creating constants that represent numbers, strings or expressions. The syntax for creating a constant using #define in the C++ is: #define token value
Syntax for #define Directive in C++
#define macro-name replacement-text
#define SQUARE_AREA(l) ((l) * (l))
#ifndef NULL
#define NULL 0
#endif
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/* #define directive in C++ language */
#include <bits/stdc++.h>
using namespace std;
void func1();
void func2();
#pragma startup func1
#pragma exit func2
void func1()
{
cout << "Inside func1()\n";
}
void func2()
{
cout << "Inside func2()\n";
}
int main()
{
void func1();
void func2();
cout << "Inside main()\n";
return 0;
}
Classes and Objects in C++ Language
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
};
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
Accessing the Data Members
The public data members of objects of a class can be accessed using the direct member access operator (.).
It is important to note that private and protected members can not be accessed directly using direct member access operator (.).
Classes and Objects in Detail
There are further interesting concepts related to C++ Classes and Objects which we will discuss in various sub-sections listed below:
• 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.
• Class Access Modifiers: A class member can be defined as public, private or protected. By default members would be assumed as private.
• 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.
• 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.
• Friend Functions: A friend function is permitted full access to private and protected members of a class.
• 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.
• this Pointer: Every object has a special pointer this which points to the object itself.
• 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.
• Static Members of a Class: Both data members and function members of a class can be declared as static.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/* using public and private in C++ Class */
// Program to illustrate the working of
// public and private in C++ Class
#include <iostream>
using namespace std;
class Room {
private:
double length;
double breadth;
double height;
public:
// function to initialize private variables
void initData(double len, double brth, double hgt) {
length = len;
breadth = brth;
height = hgt;
}
double calculateArea() {
return length * breadth;
}
double calculateVolume() {
return length * breadth * height;
}
};
int main() {
// create object of Room class
Room room1;
// pass the values of private variables as arguments
room1.initData(42.5, 30.8, 19.2);
cout << "Area of Room = " << room1.calculateArea() << endl;
cout << "Volume of Room = " << room1.calculateVolume() << endl;
return 0;
}
read() Function in C++
Read block of data. Extracts n characters from the stream and stores them in the array pointed to by s. This function simply copies a block of data, without checking its contents nor appending a null character at the end.
If the input sequence runs out of characters to extract (i.e., the end-of-file is reached) before n characters have been successfully read, the array pointed to by s contains all the characters read until that point, and both the eofbit and failbit flags are set for the stream.
Internally, the function accesses the input sequence by first constructing a sentry object (with noskipws set to true). Then (if good), it extracts characters from its associated stream buffer object as if calling its member functions sbumpc or sgetc, and finally destroys the sentry object before returning.
The number of characters successfully read and stored by this function can be accessed by calling member gcount.
Syntax for read() Function in C++
#include <fstream>
istream& read (char* s, streamsize n);
s
Pointer to an array where the extracted characters are stored.
n
Number of characters to extract. streamsize is a signed integral type.
Function returns the istream object (*this).
Errors are signaled by modifying the internal state flags:
• eofbit: The function stopped extracting characters because the input sequence has no more characters available (end-of-file reached).
• failbit: Either the function could not extract n characters or the construction of sentry failed.
• badbit: Error on stream (such as when this function catches an exception thrown by an internal operation). When set, the integrity of the stream may have been affected.
Multiple flags may be set by a single operation.
If the operation sets an internal state flag that was registered with member exceptions, the function throws an exception of member type failure.
Data races
Modifies the elements in the array pointed to by s and the stream object. Concurrent access to the same stream object may cause data races, except for the standard stream object cin when this is synchronized with stdio (in this case, no data races are initiated, although no guarantees are given on the order in which extracted characters are attributed to threads).
Exception safety
Basic guarantee: if an exception is thrown, the object is in a valid state. It throws an exception of member type failure if the resulting error state flag is not goodbit and member exceptions was set to throw for that state.
Any exception thrown by an internal operation is caught and handled by the function, setting badbit. If badbit was set on the last call to exceptions, the function rethrows the caught exception.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/* The function read() in <iostream> header file extracts n characters from the stream and stores them in the array pointed to the stream. Unlike functions put() and get() it is usually used to handle the data in binary form. */
/* extracts n characters from the stream and stores them in the array pointed by s with read() function code example. */
#include <iostream>
#include <fstream>
int main () {
std::ifstream is ("test.txt", std::ifstream::binary);
if (is) {
is.seekg (0, is.end);
int length = is.tellg();
is.seekg (0, is.beg);
char * buffer = new char [length];
std::cout << "Reading " << length << " characters... ";
is.read (buffer,length);
if (is)
std::cout << "all characters read successfully.";
else
std::cout << "error: only " << is.gcount() << " could be read";
is.close();
delete[] buffer;
}
return 0;
}
Constructors in C++ Language
In C++, constructor is a special method which is invoked automatically at the time of object creation. It is used to initialize the data members of new object generally. The constructor in C++ has the same name as class or structure.
Constructors are special class functions which performs initialization of every object. The Compiler calls the Constructor whenever an object is created. Constructors initialize values to object members after storage is allocated to the object.
Whereas, Destructor on the other hand is used to destroy the class object.
• Default Constructor: A constructor which has no argument is known as default constructor. It is invoked at the time of creating object.
Syntax for Default Constructor in C++
class_name(parameter1, parameter2, ...)
{
// constructor Definition
}
Syntax for Parameterized Constructor in C++
class class_name
{
public:
class_name(variables) //Parameterized constructor declared.
{
}
};
Syntax for Copy Constructors in C++
classname (const classname &obj) {
// body of constructor
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/* A constructor is a special type of member function that is called automatically when an object is created. In C++, a constructor has the same name as that of the class and it does not have a return type. */
#include <iostream>
using namespace std;
// declare a class
class Wall {
private:
double length;
double height;
public:
// initialize variables with parameterized constructor
Wall(double len, double hgt) {
length = len;
height = hgt;
}
// copy constructor with a Wall object as parameter
// copies data of the obj parameter
Wall(Wall &obj) {
length = obj.length;
height = obj.height;
}
double calculateArea() {
return length * height;
}
};
int main() {
// create an object of Wall class
Wall wall1(10.5, 8.6);
// copy contents of wall1 to wall2
Wall wall2 = wall1;
// print areas of wall1 and wall2
cout << "Area of Wall 1: " << wall1.calculateArea() << endl;
cout << "Area of Wall 2: " << wall2.calculateArea();
return 0;
}
#ifndef Directive in C++
The #ifndef directive of the C++ Programming Language helps in allowing the conditional compilation. The C++ Programming Language's preprocessor helps in determining only if the macro provided is not at all existed before including the specific subsequent code in the C++ compilation process. The #ifndef preprocessor only checks If the specific macro is not at all defined with the help of the #define directive. If the condition is TRUE then it will be helpful in executing the code otherwise the else code of the #ifndef will be compiled or executed only if present.
Syntax for #ifndef Directive in C++
#ifndef MACRO
//Code Statements
#else
//Code Statements which are used to include if the specific token is defined
#endif
#ifndef MACRO
The #ifndef works for the opposite condition of the #ifdef directive of the C Programming Language. The "MACRO" definition should not be defined for the specific preprocessor which is used to include the C Programming Source Code into the specific compiled application. The #ifndef must be ended with the #endif directive of the C Programming Language.
#else directive
If the #ifndef does not accept then else code statements will be printed which are actually used in including the specific which is defined.
#endif directive
The #endif directive of the C Programming Language helps in closing the #ifndef directive of the C Programming Language. It is must and should end only with the #endif C Source code directive.
The $ifndef directive usually checks/helps in seeing the specific identifier is currently not defined or not. The #ifndef preprocessor of the C Programming Language helps in allowing the conditional compilations. The preprocessor directive helps in determining whether the macro is existed or not before the subsequent code in the compilation process/ procedure.
The #ifndef directive and #if !defined identifier are equivalent directives of the C Programming Language. The #ifndef directive helps in checking the opposite condition of the #ifdef directive of the C Programming Language. If the specified identifier is not even defined or definition is removed with the help of the #undef then the condition is TRUE for nonzero value or else the condition will be FALSE.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/* #ifndef Directive in C++ language */
#define Module101
#define MyVersion 1.1
#include<iostream>
usingnamespace std;
int main(void)
{
cout<<"Sample using #define, #ifdef, #ifndef"<<endl;
cout<<" #undef, #else and #endif..."<<endl;
cout<<"-------------------------------------"<<endl;
#ifdef Module102
cout<<"\nModule102 is defined."<<endl;
#else
cout<<"\nModule102 is not defined."<<endl;
#endif
#ifndef MyVersion
cout<<"\nMyVersion is not defined"<<endl;
#else
cout<<"\nMyVersion is "<<MyVersion<<endl;
#endif
#ifdef MyRevision
cout<<"\nMy Revision is defined\n"<<endl;
#else
cout<<"\nMyRevision is not defined!"<<endl<<endl;
#endif
#undef MyVersion
#ifndef MyVersion
cout<<"MyVersion is not defined"<<endl<<endl;
#else
cout<<"MyVersion is "<<MyVersion<<endl;
#endif
return 0;
}
write() Function in C++
Write block of data. Inserts the first n characters of the array pointed by s into the stream. This function simply copies a block of data, without checking its contents: The array may contain null characters, which are also copied without stopping the copying process.
Internally, the function accesses the output sequence by first constructing a sentry object.
Then (if good), it inserts character into its associated stream buffer object as if calling its member function sputc until n characters have been written or until an insertion fails (in this case it sets the badbit flag).
Finally, it destroys the sentry object before returning.
Syntax for write() Function in C++
#include <fstream>
ostream& write (const char* s, streamsize n);
s
Pointer to an array of at least n characters.
n
Number of characters to insert. Integer value of type streamsize representing the size in characters of the block of data to write. streamsize is a signed integral type.
Function returns the ostream object (*this).
Errors are signaled by modifying the internal state flags:
• eofbit: -
• failbit: May be set if the construction of sentry failed.
• badbit: Either an insertion on the stream failed, or some other error happened (such as when this function catches an exception thrown by an internal operation). When set, the integrity of the stream may have been affected.
Multiple flags may be set by a single operation.
If the operation sets an internal state flag that was registered with member exceptions, the function throws an exception of member type failure.
Data races
Access up to n characters pointed by s. Modifies the stream object.
Concurrent access to the same stream object may cause data races, except for the standard stream objects (cout, cerr, clog) when these are synchronized with stdio (in this case, no data races are initiated, although no guarantees are given on the order in which characters from multiple threads are inserted).
Exception safety
Basic guarantee: if an exception is thrown, the object is in a valid state. It throws an exception of member type failure if the resulting error state flag is not goodbit and member exceptions was set to throw for that state.
Any exception thrown by an internal operation is caught and handled by the function, setting badbit. If badbit was set on the last call to exceptions, the function rethrows the caught exception.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/* write block of data by ostream::write function code example */
/* in order to perform a binary input/output operation using the read() and write() functions, C++ provides us a few file stream classes */
// Copy a file
#include <fstream> // std::ifstream, std::ofstream
int main () {
std::ifstream infile ("test.txt",std::ifstream::binary);
std::ofstream outfile ("new.txt",std::ofstream::binary);
// get size of file
infile.seekg (0,infile.end);
long size = infile.tellg();
infile.seekg (0);
// allocate memory for file content
char* buffer = new char[size];
// read content of infile
infile.read (buffer,size);
// write to outfile
outfile.write (buffer,size);
// release dynamically-allocated memory
delete[] buffer;
outfile.close();
infile.close();
return 0;
}
Comments in C++
The C++ comments are statements that are not executed by the compiler. The comments in C++ programming can be used to provide explanation of the code, variable, method or class. If we write comments on our code, it will be easier for us to understand the code in the future. Also, it will be easier for your fellow developers to understand the code. By the help of comments, you can hide the program code also. There are two types of comments in C++:
• Single Line comment
• Multi Line comment
Syntax for Single Line Comment in C++
/* This is a comment */
Syntax for Multi Line Comment in C++
/* C++ comments can also
* span multiple lines
*/
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/* program to illustrate use comments in C++ language */
#include <ostream>
using namespace std;
int main()
{
int x = 11; // x is a variable
cout<<x<<"\n";
/* declare and
print variable in C++ */
int x = 35;
cout<<x<<"\n";
// This is a comment
cout << "Hello World!";
/* Multi-line Comments
in C++ */
}