C++Concepts N Examples

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 17

1)

Local Variables in C++

Local variables are declared in methods and blocks. They are only accessible within that certain method
or block.

int a=7; or int a;

a=7;

Notes

A default value (depending on the data type) is assigned if the program doesn't do so.

Local variables (also can be known as "automatic" or "stack variables") are declared in the stack, which
means their memory is allocated during "compile time".

Local variables directly manipulate contents of a memory location.

stack-compile time

2)

Constants in C++

Constants are identifiers whose associated value cannot be altered during the execution of the program.

Notes

You can either use #define preprocessor form to define a constant (at the preprocessor part of the
code/beginning) or the const prefix to declare constant with a specific type (within the main code).

It is common practice to "capitalize" the entity of the variable name for constants.

Example

#define AGE 20

const int NEW_AGE = 21;

Arrays are initialized with a size, and the size cannot be modified (Vectors, on the other hand, can be
dynamically sized).

Trying to access an index outside the index range will result in an error.
3)

Vectors in C++

C++ has a vector class within the std namespace. A vector is similar to an array, in a sense where a series
of elements are stored with the same variable name. Unlike arrays, vectors are "dynamically sized",
which is a major advantage.

Syntax

vector<dataType> vectorName

Notes

Since a vector is within the std namespace, you either have to 'use' the "namespace" or type out
"std::vector".

Example

using namespace std;

//declaration

vector<int> powersOfTwo;

//adding members

powersOfTwo.push_back(1);

powersOfTwo.push_back(0);

powersOfTwo.push_back(4);

powersOfTwo.push_back(8);

//accessing

cout << "2 ^ 3 = " << powersOfTwo[3];

//accessing and changing

powersOfTwo[1] = 2;
4)

Structures in C++

A structure stores several data items and variables.

Syntax

struct structureName {

//member declarations

};

//to access a structure member

struct structureName structureInstanceName; //creating a structure instance

givenName.member; //standard members

givenName->member; //pointer members

Notes

Structures can be passed as function arguments (using the struct data type).

Structures must be declared as an instance to be accessed.

Structures can be pointers, similar to variables.

To avoid having to type out 'struct' all the time, the typedef keyword can be used when declaring the
structure. This way, 'struct' only needs to be used when declaring the structure, and can be omitted
when creating an instance of it.

Example

struct Car {

char make[50];

char model[50];

int year;
}

struct Car myCar;

myCar.year = 2014;

5)

Pointers in C++

To store a reference is to store an address in the memory of a variable. A pointer is a variable itself and
has a value whereas a reference only has a variable that it is referencing.

Syntax

dataType *pointerName = &Variable; //Pointer

dataType &referenceName = Variable; //Reference

//Memory allocation of the pointer of a specified size, usually of a certain data type

dataType *pointerName = malloc(desired_allocation_size);

delete pointerName; //Free the memory used by the pointer.

Notes

To access the memory address of any variable (stack included), use the & symbol. This is to reference.

Memory is assigned to pointer variables at runtime and not at compile time. Memory is not directly
manipulated, like with stack variables, rather the memory address stores variable's value.

Pointer variables allow the programmer to get the memory address as well as the value. By default, if
you were to access the pointer variable as you would a stack variable, you would receive the memory
address. This is known as referencing.

To access the value stored at the memory address, add an asterisk. This is known as dereferencing.

"C++ does not have garbage collection, so after allocating memory to the variable during runtime, you
need to free that memory."
Example

using namespace std;

int x = 5;

int *pointer = &x; //referencing the memory address of x, and storing it in a pointer variable

//creating a pointer variable, and allocating memory for it during runtime

int *newPointer = malloc(sizeof(int));

cout << newPointer; //will print the address in the pointer variable

*newPointer = 5; //placing a value at the memory address

cout << *newPointer; //dereferencing the pointer to print the value

delete newPointer; //free the memory once done the operation on the variable

6)

Type Definition in C++

Typedef is used to create new names for types and structures. It can save the user some typing when
using a structure or variable data type.

Syntax

typedef oldTypeName newTypeName;

Notes

A typedef is typically used to give a structure its own type, instead of having to type out 'struct
structName' every time.
Example

typedef unsigned int u_int; //giving 'unsigned int' a name of u_int

//Now, doing this

u_int myNumber;

//Is the same as doing this (except with a different variable name of course)

unsigned int myNumber2;

7)

Smart Pointers in C++

Smart pointers are pointers that are deallocated for you, as opposed to having to make sure you 'delete'
or 'free' the pointer.

Syntax

//multiple pointers can point to the same resource

std::shared_ptr<ClassType> pointerName(new ClassType(classParams));

//to create a copy of a shared pointer

std::weak_ptr<ClassType> pointerName = sharedPointerName

//restrict resource to one pointer only, no copies

std::unique_ptr<ClassType> pointerName(new ClassType(classParams));

Notes

Smart pointers were introduced in C++11.

Example

using namespace std;


//creating a pointer variable, and allocating memory for it during runtime

shared_ptr<int> newPointer(new int(5));

cout << newPointer; //will print the address in the pointer variable

cout << *newPointer; //dereferencing the pointer to print the value

//no need to call delete on the pointer

Wcslen(wide char string);


Strlen(char string)

Exception Handling

1. #include <iostream>
2. using namespace std;
3.  
4. int main()
5. {
6.    int x = -1;
7.  
8.    // Some code
9.    cout << "Before try \n";
10.    try {
11.       cout << "Inside try \n";
12.       if (x < 0)
13.       {
14.          throw x;
15.          cout << "After throw (Never executed) \n";
16.       }
17.    }
18.    catch (int x ) {
19.       cout << "Exception Caught \n";
20.    }
21.  
22.    cout << "After catch (Will be executed) \n";
23.    return 0;
24. }
Run on IDE
Output:

Before try
Inside try
Exception Caught
After catch (Will be executed)

A virtual constructor is not possible but virtual destructor is possible. Let us experiment....
#include <iostream>

using namespace std;

class Base
{
public:
Base(){
cout << "Base Constructor Called\n";
}
~Base(){
cout << "Base Destructor called\n";
}
};

class Derived1: public Base


{
public:
Derived1(){
cout << "Derived constructor called\n";
}
~Derived1(){
cout << "Derived destructor called\n";
}
};

int main()
{
Base *b = new Derived1();
delete b;
}
The above code output the following:

Base Constructor Called


Derived constructor called
Base Destructor called
The construction of derived object follow the construction rule but when we delete the "b"
pointer(base pointer) we have found that only the base destructor is call.But this must not be
happened. To do the appropriate thing we have to make the base destructor virtual. Now let see what
happen in the following:

#include <iostream>

using namespace std;

class Base
{
public:
Base(){
cout << "Base Constructor Called\n";
}
virtual ~Base(){
cout << "Base Destructor called\n";
}
};

class Derived1: public Base


{
public:
Derived1(){
cout << "Derived constructor called\n";
}
~Derived1(){
cout << "Derived destructor called\n";
}
};

int main()
{
Base *b = new Derived1();
delete b;
}
The output changed as following:

Base Constructor Called


Derived constructor called
Derived destructor called
Base Destructor called
So the destruction of base pointer(which take an allocation on derived object!) follow the destruction
rule i.e first the derived then the base. On the other hand for constructor there are nothing like virtual
constructor.
2.

Virtual Function in C++


A virtual function a member function which is declared within base class and is re-defined (Overriden) by
derived class.When you refer to a derived class object using a pointer or a reference to the base class,
you can call a virtual function for that object and execute the derived class’s version of the function.
 Virtual functions ensure that the correct function is called for an object, regardless of the type of
reference (or pointer) used for function call.
 They are mainly used to achieve Runtime polymorphism
 Functions are declared with a virtual keyword in base class.
 The resolving of function call is done at Run-time.
Rules for Virtual Functions
1. They Must be declared in public section of class.
2. Virtual functions cannot be static and also cannot be a friend function of another class.
3. Virtual functions should be accessed using pointer or reference of base class type to achieve run
time polymorphism.
4. The prototype of virtual functions should be same in base as well as derived class.
5. They are always defined in base class and overridden in derived class. It is not mandatory for
derived class to override (or re-define the virtual function), in that case base class version of
function is used.
6. A class may have virtual destructor but it cannot have a virtual constructor.
Compile-time(early binding) VS run-time(late binding) behavior of Virtual Functions
Consider the following simple program showing run-time behavior of virtual functions.

// CPP program to illustrate

// concept of Virtual Functions

#include<iostream>

using namespace std;

class base

public:

virtual void print ()

{ cout<< "print base class" <<endl; }

void show ()

{ cout<< "show base class" <<endl; }


};

class derived:public base

public:

void print ()

{ cout<< "print derived class" <<endl; }

void show ()

{ cout<< "show derived class" <<endl; }

};

int main()

base *bptr;

derived d;

bptr = &d;

//virtual function, binded at runtime

bptr->print();

// Non-virtual function, binded at compile time

bptr->show();

// C++ program to find factorial of given number


#include<iostream>
 
int factorial(int n)
{
    // single line to find factorial
    return (n==1 || n==0) ? 1: n * factorial(n - 1);
}
 
// Driver Code
int main()
{
    int num = 5;
    printf ("Factorial of %d is %d", num, factorial(num));
    return 0;
}
 
// C/C++ program to swap two variables in single line
#include <stdio.h>
int main()
{
    int x = 5, y = 10;
    (x ^= y), (y ^= x), (x ^= y);
    printf("After Swapping values of x and y are %d %d",
            x, y);
    return 0;
}

DYNAMIC CASTING

dynamic_cast in C++ can be used to perform type safe down casting. dynamic_cast is run
time polymorphism. The dynamic_cast operator, which safely converts from a pointer (or
reference) to a base type to a pointer (or reference) to a derived type.

LINUX OS
#include <stdio.h>
#include <stdlib.h>
 
int main()
{
   // Running Linux OS command using system
   system("shutdown -P now");
   
   return 0;
}

We will make use of system() from < stdlib.h > to perform a system operation with the
help of a C program.To perform any of the afore-mentioned system operation we will
code as:
#include <stdio.h>

#include <stdlib.h>

 
int main()

  system("c:\\windows\\system32\\shutdown /i");
  return 0;

Run on IDE

The argument to the system function is the path to OS and /i is one of the entity from
the vast options available to us.To view the options, we run cmd and type:

C:\Users\User>shutdown

The shutdown command presents us with a list of options available for us.These are :

system() in C/C++
system() is used to invoke an operating system command from a C/C++ program.

int system(const char *command);

Note: stdlib.h or cstdlib needs to be included to call system.


Using system(), we can execute any command that can run on terminal if operating system allows. For
example, we can call system(“dir”) on Windows and system(“ls”) to list contents of a directory.

Writing a C/C++ program that compiles and runs other program?


We can invoke gcc from our program using system(). See below code written for Linux. We can easily
change code to run on windows.
// A C++ program that compiles and runs another C++

// program
#include <bits/stdc++.h>

using namespace std;

int main ()

    char filename[100];

    cout << "Enter file name to compile ";

    cin.getline(filename, 100);

 
    // Build command to execute.  For example if the input

    // file name is a.cpp, then str holds "gcc -o a.out a.cpp"

    // Here -o is used to specify executable file name

    string str = "gcc ";

    str = str + " -o a.out " + filename;

 
    // Convert string to const char * as system requires

    // parameter of type const char *

    const char *command = str.c_str();

 
    cout << "Compiling file using " << command << endl;

    system(command);

 
    cout << "\nRunning file ";

    system("./a.out");

 
    return 0;

system() vs using library functions:


Some common uses of system() in Windows OS are, system(“pause”) which is used to
execute pause command and make the screen/terminal wait for a key press, and
system(“cls”) which is used to make the screen/terminal clear.
However, making a call to system command should be avoided due to the following
reasons:
1. It’s a very expensive and resource heavy function call
2. It’s not portable: Using system() makes the program very non-portable i.e. this works only on
systems that have the pause command at the system level, like DOS or Windows. But not Linux,
MAC OSX and most others.
Let us take a simple C++ code to output Hello World using system(“pause”):
// A C++ program that pauses screen at the end in Windows OS

#include <iostream>

using namespace std;

int main ()

    cout << "Hello World!" << endl;

    system("pause");

    return 0;

Run on IDE

The output of the above program in Windows OS:

Hello World!

Press any key to continue…

This program is OS dependent and uses following heavy steps.


 It suspends your program and simultaneously calls the operating system to opens the operating
system shell.
 The OS finds the pause and allocate the memory to execute the command.
 It then deallocate the memory, exit the Operating System and resumes the program.
Instead of using the system(“pause”), we can also use the functions that are defined
natively in C/C++.
Let us take a simple example to output Hello World with cin.get():
// Replacing system() with library function

#include <iostream>

#include <cstdlib>

using namespace std;

int main ()

{
    cout << "Hello World!" << endl;

    cin.get();  // or getchar()

    return 0;

Run on IDE

The output of the program is :

Hello World!

Thus, we see that, both system(“pause”) and cin.get() are actually performing a wait for


a key to be pressed, but, cin.get() is not OS dependent and neither it follows the above
mentioned steps to pause the program.
Similarly, in C language, getchar() can be used to pause the program without printing
the message “Press any key to continue…”.
A common way to check if we can run commands using system() in an OS?
If we pass null pointer in place of string for command parameter, system returns nonzero
if command processor exists (or system can run). Otherwise returns 0.
// C++ program to check if we can run commands using

// system()

#include <iostream>

#include <cstdlib>

using namespace std;

int main ()

    if (system(NULL))

       cout << "Command processor exists";

    else

       cout << "Command processor doesn't exists";

 
    return 0;

Run on IDE

Note that the above programs may not work on online compiler as System command is
disabled in most of the online compilers including GeeksforGeeks IDE.
This article is contributed by Subhankar Das. If you like GeeksforGeeks and would like
to contribute, you can also write an article and mail your article to
[email protected]. See your article appearing on the GeeksforGeeks main
page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

You might also like