Happy Codings - Programming Code Examples

C++ Programming Code Examples

C++ > Games Code Examples

Dynamic binding of an Interface from a Dynamic loaded DLL

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 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
/* Dynamic binding of an Interface from a Dynamic loaded DLL */ class IRenderer { public: virtual ~IRenderer( ) { } virtual int Init( int ) = 0; }; //DLL Header: DllName.h #ifdef DLLNAME_EXPORTS # define CLASS_DECLSPEC __declspec(dllexport) #else # define CLASS_DECLSPEC __declspec(dllimport) #endif #include "RendererInterface.h" template<class T> class TSingleton { private: static T* object; static int refcount; public: TSingleton( ) { if( !refcount++ ) object = new T; } ~TSingleton( ) { if( !--refcount ) { delete object; object = NULL; } } const T& GetObject( ) { return *object; } static void* operator new( size_t ) { return NULL; } static void* operator new[]( size_t ) { return NULL; } static const int& RefCount( ) { return refcount; } }; template<class T>T* TSingleton<T>::object = NULL; template<class T>int TSingleton<T>::refcount = 0; class CD3d : public IRenderer { public: virtual ~CD3d( ) { } virtual int Init( int ); }; int CD3d::Init( int i ) { return ++i; } //DLL Source: DllName.cpp static bool wasCreated = false; extern "C" { CLASS_DECLSPEC IRenderer* __cdecl CreateInstance( ) { static TSingleton<CD3d> d3d; wasCreated = true; return const_cast<CD3d*>( &d3d.GetObject( ) ); } CLASS_DECLSPEC IRenderer* __cdecl GetInstance( ) { assert( false != wasCreated ); TSingleton<CD3d> d3d; return const_cast<CD3d*>( &d3d.GetObject( ) ); } } BOOL APIENTRY DllMain( HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: break; case DLL_THREAD_ATTACH: break; case DLL_THREAD_DETACH: break; case DLL_PROCESS_DETACH: break; } return TRUE; } //Application SceneGraph Header: sg.h class CSceneGraph { private: typedef IRenderer* (__cdecl * funcCreateInstance)( ); IRenderer* iRen; HMODULE hMod; funcCreateInstance CreateInstance; public: CSceneGraph( ) { hMod = LoadLibrary( "dllname.dll" ); CreateInstance = reinterpret_cast<funcCreateInstance>( GetProcAddress( hMod, "CreateInstance" ) ); iRen = CreateInstance( ); //i should return 1 if binding worked int i = iRen->Init( 0 ); } ~CSceneGraph( ) { FreeLibrary( hMod ) } }
Class Templates in C++
Templates are powerful features of C++ which allows us to write generic programs. Similar to function templates, we can use class templates to create a single class to work with different data types. Class templates come in handy as they can make our code shorter and more manageable. A class template starts with the keyword template followed by template parameter(s) inside <> which is followed by the class declaration.
Declaration for Class Template in C++
template <class T> class className { private: T var; ... .. ... public: T functionName(T arg); ... .. ... };
T
template argument
var
a member variable T is the template argument which is a placeholder for the data type used, and class is a keyword. Inside the class body, a member variable var and a member function functionName() are both of type T. Creating a class template object: Once we've declared and defined a class template, we can create its objects in other classes or functions (such as the main() function) with the following syntax:
className<dataType> classObject;
Defining a class member outside the class template: Suppose we need to define a function outside of the class template. We can do this with the following code:
template <class T> class ClassName { ... .. ... // Function prototype returnType functionName(); }; // Function definition template <class T> returnType ClassName<T>::functionName() { // code }
Notice that the code template <class T> is repeated while defining the function outside of the class. This is necessary and is part of the syntax. C++ class templates with multiple parameters: In C++, we can use multiple template parameters and even use default arguments for those parameters.
template <class T, class U, class V = int> class ClassName { private: T member1; U member2; V member3; ... .. ... public: ... .. ... };
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
/* 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. */ #include <iostream> using namespace std; template <typename T> class Array { private: T *ptr; int size; public: Array(T arr[], int s); void print(); }; template <typename T> Array<T>::Array(T arr[], int s) { ptr = new T[s]; size = s; for(int i = 0; i < size; i++) ptr[i] = arr[i]; } template <typename T> void Array<T>::print() { for (int i = 0; i < size; i++) cout<<" "<<*(ptr + i); cout<<endl; } int main() { int arr[5] = {1, 2, 3, 4, 5}; Array<int> a(arr, 5); a.print(); return 0; }
Memory Management new Operator in C++
Allocate storage space. Default allocation functions (single-object form). A new operator is used to create the object while a delete operator is used to delete the object. When the object is created by using the new operator, then the object will exist until we explicitly use the delete operator to delete the object. Therefore, we can say that the lifetime of the object is not related to the block structure of the program.
Syntax for new Operator in C++
#include <new> //throwing (1) void* operator new (std::size_t size); //nothrow (2) void* operator new (std::size_t size, const std::nothrow_t& nothrow_value) noexcept; //placement (3) void* operator new (std::size_t size, void* ptr) noexcept;
size
Size in bytes of the requested memory block. This is the size of the type specifier in the new-expression when called automatically by such an expression. If this argument is zero, the function still returns a distinct non-null pointer on success (although dereferencing this pointer leads to undefined behavior). size_t is an integral type.
nothrow_value
The constant nothrow. This parameter is only used to distinguish it from the first version with an overloaded version. When the nothrow constant is passed as second parameter to operator new, operator new returns a null-pointer on failure instead of throwing a bad_alloc exception. nothrow_t is the type of constant nothrow.
ptr
A pointer to an already-allocated memory block of the proper size. If called by a new-expression, the object is initialized (or constructed) at this location. For the first and second versions, function returns a pointer to the newly allocated storage space. For the third version, ptr is returned. • (1) throwing allocation: Allocates size bytes of storage, suitably aligned to represent any object of that size, and returns a non-null pointer to the first byte of this block. On failure, it throws a bad_alloc exception. • (2) nothrow allocation: Same as above (1), except that on failure it returns a null pointer instead of throwing an exception. The default definition allocates memory by calling the the first version: ::operator new (size). If replaced, both the first and second versions shall return pointers with identical properties. • (3) placement: Simply returns ptr (no storage is allocated). Notice though that, if the function is called by a new-expression, the proper initialization will be performed (for class objects, this includes calling its default constructor). The default allocation and deallocation functions are special components of the standard library; They have the following unique properties: • Global: All three versions of operator new are declared in the global namespace, not within the std namespace. • Implicit: The allocating versions ((1) and (2)) are implicitly declared in every translation unit of a C++ program, no matter whether header <new> is included or not. • Replaceable: The allocating versions ((1) and (2)) are also replaceable: A program may provide its own definition that replaces the one provided by default to produce the result described above, or can overload it for specific types. If set_new_handler has been used to define a new_handler function, this new-handler function is called by the default definitions of the allocating versions ((1) and (2)) if they fail to allocate the requested storage. operator new can be called explicitly as a regular function, but in C++, new is an operator with a very specific behavior: An expression with the new operator, first calls function operator new (i.e., this function) with the size of its type specifier as first argument, and if this is successful, it then automatically initializes or constructs the object (if needed). Finally, the expression evaluates as a pointer to the appropriate type.
Data races
Modifies the storage referenced by the returned value. Calls to allocation and deallocation functions that reuse the same unit of storage shall occur in a single total order where each deallocation happens entirely before the next allocation. This shall also apply to the observable behavior of custom replacements for this function.
Exception safety
The first version (1) throws bad_alloc if it fails to allocate storage. Otherwise, it throws no exceptions (no-throw guarantee).
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 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
/* C++ allows us to allocate the memory of a variable or an array in run time. This is known as dynamic memory allocation. The new operator denotes a request for memory allocation on the Free Store. If sufficient memory is available, new operator initializes the memory and returns the address of the newly allocated and initialized memory to the pointer variable. */ /* Allocate storage space by operator new */ // C++ program code example to illustrate dynamic allocation and deallocation of memory using new and delete #include <iostream> using namespace std; int main () { // Pointer initialization to null int* p = NULL; // Request memory for the variable // using new operator p = new(nothrow) int; if (!p) cout << "allocation of memory failed\n"; else { // Store value at allocated address *p = 29; cout << "Value of p: " << *p << endl; } // Request block of memory // using new operator float *r = new float(75.25); cout << "Value of r: " << *r << endl; // Request block of memory of size n int n = 5; int *q = new(nothrow) int[n]; if (!q) cout << "allocation of memory failed\n"; else { for (int i = 0; i < n; i++) q[i] = i+1; cout << "Value store in block of memory: "; for (int i = 0; i < n; i++) cout << q[i] << " "; } // freed the allocated memory delete p; delete r; // freed the block of allocated memory delete[] q; return 0; }
Virtual Functions in C++
A C++ virtual function is a member function in the base class that you redefine in a derived class. It is declared using the virtual keyword. It is used to tell the compiler to perform dynamic linkage or late binding on the function. There is a necessity to use the single pointer to refer to all the objects of the different classes. So, we create the pointer to the base class that refers to all the derived objects. But, when base class pointer contains the address of the derived class object, always executes the base class function. This issue can only be resolved by using the 'virtual' function. A 'virtual' is a keyword preceding the normal declaration of a function. When the function is made virtual, C++ determines which function is to be invoked at the runtime based on the type of the object pointed by the base class pointer. In late binding function call is resolved during runtime. Therefore compiler determines the type of object at runtime, and then binds the function call. • Virtual functions must be members of some class. • Virtual functions cannot be static members. • They are accessed through object pointers. • They can be a friend of another class. • A virtual function must be defined in the base class, even though it is not used. • The prototypes of a virtual function of the base class and all the derived classes must be identical. If the two functions with the same name but different prototypes, C++ will consider them as the overloaded functions. • We cannot have a virtual constructor, but we can have a virtual destructor. • Consider the situation when we don't use the virtual keyword. A virtual function is not used for performing any task. It only serves as a placeholder. When the function has no definition, such function is known as "do-nothing" function. The "do-nothing" function is known as a pure virtual function. A pure virtual function is a function declared in the base class that has no definition relative to the base class. A class containing the pure virtual function cannot be used to declare the objects of its own, such classes are known as abstract base classes. The main objective of the base class is to provide the traits to the derived classes and to create the base pointer used for achieving the runtime polymorphism.
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 47
// C++ program to demonstrate the use of virtual function // CPP program to illustrate concept of Virtual Functions #include<iostream> using namespace std; class base { public: virtual void print() { cout << "print base class\n"; } void show() { cout << "show base class\n"; } }; class derived : public base { public: void print() { cout << "print derived class\n"; } void show() { cout << "show derived class\n"; } }; int main() { base *bptr; derived d; bptr = &d; // Virtual function, binded at runtime bptr->print(); // Non-virtual function, binded at compile time bptr->show(); return 0; }
main() Function in C++
A program shall contain a global function named main, which is the designated start of the program in hosted environment. main() function is the entry point of any C++ program. It is the point at which execution of program is started. When a C++ program is executed, the execution control goes directly to the main() function. Every C++ program have a main() function.
Syntax for main() Function in C++
void main() { ............ ............ }
void
void is a keyword in C++ language, void means nothing, whenever we use void as a function return type then that function nothing return. here main() function no return any value.
main
main is a name of function which is predefined function in C++ library. In place of void we can also use int return type of main() function, at that time main() return integer type value. 1) It cannot be used anywhere in the program a) in particular, it cannot be called recursively b) its address cannot be taken 2) It cannot be predefined and cannot be overloaded: effectively, the name main in the global namespace is reserved for functions (although it can be used to name classes, namespaces, enumerations, and any entity in a non-global namespace, except that a function called "main" cannot be declared with C language linkage in any namespace). 3) It cannot be defined as deleted or (since C++11) declared with C language linkage, constexpr (since C++11), consteval (since C++20), inline, or static. 4) The body of the main function does not need to contain the return statement: if control reaches the end of main without encountering a return statement, the effect is that of executing return 0;. 5) Execution of the return (or the implicit return upon reaching the end of main) is equivalent to first leaving the function normally (which destroys the objects with automatic storage duration) and then calling std::exit with the same argument as the argument of the return. (std::exit then destroys static objects and terminates the program). 6) (since C++14) The return type of the main function cannot be deduced (auto main() {... is not allowed). 7) (since C++20) The main function cannot be a coroutine.
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
/* simple code example by main() function in C++ */ #include <iostream> using namespace std; int main() { int day = 4; switch (day) { case 1: cout << "Monday"; break; case 2: cout << "Tuesday"; break; case 3: cout << "Wednesday"; break; case 4: cout << "Thursday"; break; case 5: cout << "Friday"; break; case 6: cout << "Saturday"; break; case 7: cout << "Sunday"; break; } return 0; }
Function Templates in C++
A C++ template is a powerful feature added to C++. It allows you to define the generic classes and generic functions and thus provides support for generic programming. Generic programming is a technique where generic types are used as parameters in algorithms so that they can work for a variety of data types. We can define a template for a function. For example, if we have an add() function, we can create versions of the add function for adding the int, float or double type values.
Syntax for Function Templates in C++
template < class Ttype> ret_type func_name(parameter_list) { // body of function. }
Ttype
a placeholder name
class
specify a generic type Where Ttype: It is a placeholder name for a data type used by the function. It is used within the function definition. It is only a placeholder that the compiler will automatically replace this placeholder with the actual data type. class: A class keyword is used to specify a generic type in a template declaration. • Generic functions use the concept of a function template. Generic functions define a set of operations that can be applied to the various types of data. • The type of the data that the function will operate on depends on the type of the data passed as a parameter. • For example, Quick sorting algorithm is implemented using a generic function, it can be implemented to an array of integers or array of floats. • A Generic function is created by using the keyword template. The template defines what function will do. Function templates with multiple parameters: We can use more than one generic type in the template function by using the comma to separate the list.
template<class T1, class T2,.....> return_type function_name (arguments of type T1, T2....) { // body of function. }
Overloading a function template: We can overload the generic function means that the overloaded template functions can differ in the parameter list. Generic functions perform the same operation for all the versions of a function except the data type differs.
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
/* function templates in C++ language */ /* adding two numbers using function templates */ #include <iostream> using namespace std; template <typename T> T add(T num1, T num2) { return (num1 + num2); } int main() { int result1; double result2; // calling with int parameters result1 = add<int>(2, 3); cout << "2 + 3 = " << result1 << endl; // calling with double parameters result2 = add<double>(2.2, 3.3); cout << "2.2 + 3.3 = " << result2 << endl; return 0; }
Static Keyword in C++
Static is a keyword in C++ used to give special characteristics to an element. Static elements are allocated storage only once in a program lifetime in static storage area. And they have a scope till the program lifetime. In C++, static is a keyword or modifier that belongs to the type not instance. So instance is not required to access the static members. In C++, static can be field, method, constructor, class, properties, operator and event. Advantage of C++ static keyword: Memory efficient. Now we don't need to create instance for accessing the static members, so it saves memory. Moreover, it belongs to the type, so it will not get memory each time when instance is created. C++ Static Field: A field which is declared as static is called static field. Unlike instance field which gets memory each time whenever you create object, there is only one copy of static field created in the memory. It is shared to all the objects. It is used to refer the common property of all objects such as rateOfInterest in case of Account, companyName in case of Employee etc. Static variables inside functions: Static variables when used inside function are initialized only once, and then they hold there value even through function calls. These static variables are stored on static storage area , not in stack.
void counter() { static int count=0; cout << count++; } int main(0 { for(int i=0;i<5;i++) { counter(); } }
Static class objects: Static keyword works in the same way for class objects too. Objects declared static are allocated storage in static storage area, and have scope till the end of program. Static objects are also initialized using constructors like other normal objects. Assignment to zero, on using static keyword is only for primitive datatypes, not for user defined datatypes.
class Abc { int i; public: Abc() { i=0; cout << "constructor"; } ~Abc() { cout << "destructor"; } }; void f() { static Abc obj; } int main() { int x=0; if(x==0) { f(); } cout << "END"; }
Static data member in class: Static data members of class are those members which are shared by all the objects. Static data member has a single piece of storage, and is not available as separate copy with each object, like other non-static data members. Static member variables (data members) are not initialied using constructor, because these are not dependent on object initialization. Also, it must be initialized explicitly, always outside the class. If not initialized, Linker will give error.
class X { public: static int i; X() { // construtor }; }; int X::i=1; int main() { X obj; cout << obj.i; // prints value of i }
Static member functions: These functions work for the class as whole rather than for a particular object of a class. It can be called using an object and the direct member access . operator. But, its more typical to call a static member function by itself, using class name and scope resolution :: operator.
class X { public: static void f() { // statement } }; int main() { X::f(); // calling member function directly with class name }
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
/* static keyword has different meanings when used with different types simple code example */ // CPP program to illustrate class objects as static #include<iostream> using namespace std; class Happy { int i = 0; public: Happy() { i = 0; cout << "Inside Constructor\n"; } ~Happy() { cout << "Inside Destructor\n"; } }; int main() { int x = 0; if (x==0) { static Happy obj; } cout << "End of main\n"; }
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 };
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 (.). 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; }
Destructors in C++
A destructor is a special member function that works just opposite to constructor, unlike constructors that are used for initializing an object, destructors destroy (or delete) the object. Destructors in C++ are members functions in a class that delete an object. They are called when the class object goes out of scope such as when the function ends, the program ends, a delete variable is called etc. Destructors are different from normal member functions as they don't take any argument and don't return anything. Also, destructors have the same name as their class and their name is preceded by a tilde(~).
Syntax for Destructor in C++
~class_name() { //Some code }
Similar to constructor, the destructor name should exactly match with the class name. A destructor declaration should always begin with the tilde(~) symbol as shown in the syntax above. A destructor is automatically called when: • The program finished execution. • When a scope (the { } parenthesis) containing local variable ends. • When you call the delete operator.
Destructor rules
• Name should begin with tilde sign(~) and must match class name. • There cannot be more than one destructor in a class. • Unlike constructors that can have parameters, destructors do not allow any parameter. • They do not have any return type, just like constructors. • When you do not specify any destructor in a class, compiler generates a default destructor and inserts it into your code.
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
/* Destructor is an instance member function which is invoked automatically whenever an object is going to be destroyed. Meaning, a destructor is the last function that is going to be called before an object is destroyed. The thing is to be noted here, if the object is created by using new or the constructor uses new to allocate memory which resides in the heap memory or the free store, the destructor should use delete to free the memory. */ #include <iostream> using namespace std; class HelloWorld{ public: //Constructor HelloWorld(){ cout<<"Constructor is called"<<endl; } //Destructor ~HelloWorld(){ cout<<"Destructor is called"<<endl; } //Member function void display(){ cout<<"Hello World!"<<endl; } }; int main(){ //Object created HelloWorld obj; //Member function called obj.display(); return 0; }
#include Directive in C++
#include is a way of including a standard or user-defined file in the program and is mostly written at the beginning of any C/C++ program. This directive is read by the preprocessor and orders it to insert the content of a user-defined or system header file into the following program. These files are mainly imported from an outside source into the current program. The process of importing such files that might be system-defined or user-defined is known as File Inclusion. This type of preprocessor directive tells the compiler to include a file in the source code program.
Syntax for #include Directive in C++
#include "user-defined_file"
Including using " ": When using the double quotes(" "), the preprocessor access the current directory in which the source "header_file" is located. This type is mainly used to access any header files of the user's program or user-defined files.
#include <header_file>
Including using <>: While importing file using angular brackets(<>), the the preprocessor uses a predetermined directory path to access the file. It is mainly used to access system header files located in the standard system directories. Header File or Standard files: This is a file which contains C/C++ function declarations and macro definitions to be shared between several source files. Functions like the printf(), scanf(), cout, cin and various other input-output or other standard functions are contained within different header files. So to utilise those functions, the users need to import a few header files which define the required functions. User-defined files: These files resembles the header files, except for the fact that they are written and defined by the user itself. This saves the user from writing a particular function multiple times. Once a user-defined file is written, it can be imported anywhere in the program using the #include preprocessor. • In #include directive, comments are not recognized. So in case of #include <a//b>, a//b is treated as filename. • In #include directive, backslash is considered as normal text not escape sequence. So in case of #include <a\nb>, a\nb is treated as filename. • You can use only comment after filename otherwise it will give error.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/* using #include directive in C language */ #include <stdio.h> int main() { /* * C standard library printf function * defined in the stdio.h header file */ printf("I love you Clementine"); printf("I love you so much"); printf("HappyCodings"); return 0; }
Casting Operators in C++
A cast is a special operator that forces one data type to be converted into another. As an operator, a cast is unary and has the same precedence as any other unary operator. Converting an expression of a given type into another type is known as type-casting. The most general cast supported by most of the C++ compilers is as follows:
(type) expression
Where type is the desired data type. There are other casting operators supported by C++, they are listed below: • const_cast<type> (expr): The const_cast operator is used to explicitly override const and/or volatile in a cast. The target type must be the same as the source type except for the alteration of its const or volatile attributes. This type of casting manipulates the const attribute of the passed object, either to be set or removed. • dynamic_cast<type> (expr): The dynamic_cast performs a runtime cast that verifies the validity of the cast. If the cast cannot be made, the cast fails and the expression evaluates to null. A dynamic_cast performs casts on polymorphic types and can cast a A* pointer into a B* pointer only if the object being pointed to actually is a B object. • reinterpret_cast<type> (expr): The reinterpret_cast operator changes a pointer to any other type of pointer. It also allows casting from pointer to an integer type and vice versa. • static_cast<type> (expr): The static_cast operator performs a nonpolymorphic cast. For example, it can be used to cast a base class pointer into a derived class pointer. All of the above-mentioned casting operators will be used while working with classes and objects. For now, try the following example to understand a simple cast operators available in C++. Copy and paste the following C++ program in test.cpp file and compile and run this program.
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
/* Type casting of the variables in the C++ programming language. Type casting refers to the conversion of one data type to another in a program. Typecasting can be done in two ways: automatically by the compiler and manually by the programmer or user. Type Casting is also known as Type Conversion. */ /* code example to demonstrate the casting of one variable to another using the implicit type casting in C++. */ #include <iostream> using namespace std; int main () { short x = 200; int y; y = x; cout << " Implicit Type Casting " << endl; cout << " The value of x: " << x << endl; cout << " The value of y: " << y << endl; int num = 20; char ch = 'a'; int res = 20 + 'a'; cout << " Type casting char to int data type ('a' to 20): " << res << endl; float val = num + 'A'; cout << " Type casting from int data to float type: " << val << endl; return 0; }
If Else Statement in C++
In computer programming, we use the if statement to run a block code only when a certain condition is met. An if statement can be followed by an optional else statement, which executes when the boolean expression is false. There are three forms of if...else statements in C++: • if statement, • if...else statement, • if...else if...else statement,
Syntax for If Statement in C++
if (condition) { // body of if statement }
The if statement evaluates the condition inside the parentheses ( ). If the condition evaluates to true, the code inside the body of if is executed. If the condition evaluates to false, the code inside the body of if is skipped.
Syntax for If...Else Statement
if (condition) { // block of code if condition is true } else { // block of code if condition is false }
The if..else statement evaluates the condition inside the parenthesis. If the condition evaluates true, the code inside the body of if is executed, the code inside the body of else is skipped from execution. If the condition evaluates false, the code inside the body of else is executed, the code inside the body of if is skipped from execution. The if...else statement is used to execute a block of code among two alternatives. However, if we need to make a choice between more than two alternatives, we use the if...else if...else statement.
Syntax for If...Else...Else If Statement in C++
if (condition1) { // code block 1 } else if (condition2){ // code block 2 } else { // code block 3 }
• If condition1 evaluates to true, the code block 1 is executed. • If condition1 evaluates to false, then condition2 is evaluated. • If condition2 is true, the code block 2 is executed. • If condition2 is false, the code block 3 is executed. There can be more than one else if statement but only one if and else statements. In C/C++ if-else-if ladder helps user decide from among multiple options. The C/C++ if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the C else-if ladder is bypassed. If none of the conditions is true, then the final else statement will be executed.
Syntax for If Else If Ladder in C++
if (condition) statement 1; else if (condition) statement 2; . . else statement;
Working of the if-else-if ladder: 1. Control falls into the if block. 2. The flow jumps to Condition 1. 3. Condition is tested. If Condition yields true, goto Step 4. If Condition yields false, goto Step 5. 4. The present block is executed. Goto Step 7. 5. The flow jumps to Condition 2. If Condition yields true, goto step 4. If Condition yields false, goto Step 6. 6. The flow jumps to Condition 3. If Condition yields true, goto step 4. If Condition yields false, execute else block. Goto Step 7. 7. Exits the if-else-if ladder. • The if else ladder statement in C++ programming language is used to check set of conditions in sequence. • This is useful when we want to selectively executes one code block(out of many) based on certain conditions. • It allows us to check for multiple condition expressions and execute different code blocks for more than two conditions. • A condition expression is tested only when all previous if conditions in if-else ladder is false. • If any of the conditional expression evaluates to true, then it will execute the corresponding code block and exits whole if-else ladder.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
/* If Else Statement in C++ Language */ #include <iostream> using namespace std; int main () { // local variable declaration: int a = 100; // check the boolean condition if( a < 20 ) { // if condition is true then print the following cout << "a is less than 20;" << endl; } else { // if condition is false then print the following cout << "a is not less than 20;" << endl; } cout << "value of a is : " << a << endl; return 0; }
Break Statement in C++
Break statement in C++ is a loop control statement defined using the break keyword. It is used to stop the current execution and proceed with the next one. When a compiler calls the break statement, it immediately stops the execution of the loop and transfers the control outside the loop and executes the other statements. In the case of a nested loop, break the statement stops the execution of the inner loop and proceeds with the outer loop. The statement itself says it breaks the loop. When the break statement is called in the program, it immediately terminates the loop and transfers the flow control to the statement mentioned outside the loop.
Syntax for Break Statement in C++
// jump-statement; break;
The break statement is used in the following scenario: • When a user is not sure about the number of iterations in the program. • When a user wants to stop the program based on some condition. The break statement terminates the loop where it is defined and execute the other. If the condition is mentioned in the program, based on the condition, it executes the loop. If the condition is true, it executes the conditional statement, and if the break statement is mentioned, it will immediately break the program. otherwise, the loop will iterate until the given condition fails. if the condition is false, it stops the program.
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
/* break statement with while loop code example */ // program to find the sum of positive numbers // if the user enters a negative numbers, break ends the loop // the negative number entered is not added to sum #include <iostream> using namespace std; int main() { int number; int sum = 0; while (true) { // take input from the user cout << "Enter a number: "; cin >> number; // break condition if (number < 0) { break; } // add all positive numbers sum += number; } // display the sum cout << "The sum is " << sum << endl; return 0; }
assert() Function in C++
Evaluate assertion. If the argument expression of this macro with functional form compares equal to zero (i.e., the expression is false), a message is written to the standard error device and abort is called, terminating the program execution. The specifics of the message shown depend on the particular library implementation, but it shall at least include: the expression whose assertion failed, the name of the source file, and the line number where it happened. A usual expression format is: Assertion failed: expression, file filename, line line number
Syntax for assert() Function in C++
#include <assert.h> void assert (int expression);
expression
Expression to be evaluated. If this expression evaluates to 0, this causes an assertion failure that terminates the program. This function does not return any value. This macro is disabled if, at the moment of including <assert.h>, a macro with the name NDEBUG has already been defined. This allows for a coder to include as many assert calls as needed in a source code while debugging the program and then disable all of them for the production version by simply including a line like: #define NDEBUG at the beginning of the code, before the inclusion of <assert.h>. Therefore, this macro is designed to capture programming errors, not user or run-time errors, since it is generally disabled after a program exits its debugging phase.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
/* Assertions are statements used to test assumptions made by programmers. */ #include <iostream> using namespace std; #define NDEBUG #include <assert.h> int main() { int a = 5; /* Code just mistakenly changes the value of a from 5 to let us say 6 */ a = 6; /* Now we can check for the validity of a being 5 till the end of program */ assert(a == 5); cout << "Successful" << endl; 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 }
• Parameterized Constructor: In C++, a constructor with parameters is known as a parameterized constructor. This is the preferred method to initialize member data. These are the constructors with parameter. Using this Constructor you can provide different values to data members of different objects, by passing the appropriate values as argument.
Syntax for Parameterized Constructor in C++
class class_name { public: class_name(variables) //Parameterized constructor declared. { } };
• Copy Constructors: These are special type of Constructors which takes an object as argument, and is used to copy values of data members of one object into other object.
Syntax for Copy Constructors in C++
classname (const classname &obj) { // body of 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. The copy constructor is used to - • Initialize one object from another of the same type. • Copy an object to pass it as an argument to a function. • Copy an object to return it from a function. If a copy constructor is not defined in a class, the compiler itself defines one.If the class has pointer variables and has some dynamic memory allocations, then it is a must to have a copy constructor. The most common form of copy constructor is shown here.
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; }
Switch Case Statement in C++
Switch statement in C tests the value of a variable and compares it with multiple cases. Once the case match is found, a block of statements associated with that particular case is executed. Each case in a block of a switch has a different name/number which is referred to as an identifier. The value provided by the user is compared with all the cases inside the switch block until the match is found. If a case match is NOT found, then the default statement is executed, and the control goes out of the switch block.
Syntax for Switch Case Statement in C++
switch( expression ) { case value-1: Block-1; Break; case value-2: Block-2; Break; case value-n: Block-n; Break; default: Block-1; Break; } Statement-x;
• The expression can be integer expression or a character expression. • Value-1, 2, n are case labels which are used to identify each case individually. Remember that case labels should not be same as it may create a problem while executing a program. Suppose we have two cases with the same label as '1'. Then while executing the program, the case that appears first will be executed even though you want the program to execute a second case. This creates problems in the program and does not provide the desired output. • Case labels always end with a colon ( : ). Each of these cases is associated with a block. • A block is nothing but multiple statements which are grouped for a particular case. • Whenever the switch is executed, the value of test-expression is compared with all the cases which we have defined inside the switch. Suppose the test expression contains value 4. This value is compared with all the cases until case whose label four is found in the program. As soon as a case is found the block of statements associated with that particular case is executed and control goes out of the switch. • The break keyword in each case indicates the end of a particular case. If we do not put the break in each case then even though the specific case is executed, the switch in C will continue to execute all the cases until the end is reached. This should not happen; hence we always have to put break keyword in each case. Break will terminate the case once it is executed and the control will fall out of the switch. • The default case is an optional one. Whenever the value of test-expression is not matched with any of the cases inside the switch, then the default will be executed. Otherwise, it is not necessary to write default in the switch. • Once the switch is executed the control will go to the statement-x, and the execution of a program will continue.
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
/* the switch statement helps in testing the equality of a variable against a set of values */ #include <iostream> using namespace std; int main () { // local variable declaration: char grade = 'D'; switch(grade) { case 'A' : cout << "Excellent!" << endl; break; case 'B' : case 'C' : cout << "Well done" << endl; break; case 'D' : cout << "You passed" << endl; break; case 'F' : cout << "Better try again" << endl; break; default : cout << "Invalid grade" << endl; } cout << "Your grade is " << grade << endl; return 0; }
#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
• Using #define to create Macros Macros also follow the same structure as Symbolic Constants; however, Macros allow arguments to be included in the identifier:
#define SQUARE_AREA(l) ((l) * (l))
Unlike in functions, the argument here is enclosed in parenthesis in the identifier and does not have a type associated with it. Before compilation, the compiler will replace every instance of SQUARE_AREA(l) by ((l) * (l)), where l can be any expression. • Conditional Compilation There are several directives, which can be used to compile selective portions of your program's source code. This process is called conditional compilation. The conditional preprocessor construct is much like the 'if' selection structure. Consider the following preprocessor code:
#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; }


Read the comments in the following program to understand each part of the program. This is a "default constructor" of the class, you do note that it's name is same as class name and
in C++, "bitwise operators" are similar to the Logic operators, but they perform the same logical operations on bits. All data in memory is represented in the "binary form". Variables