C++Concepts N Examples
C++Concepts N Examples
C++Concepts N Examples
Local variables are declared in methods and blocks. They are only accessible within that certain method
or block.
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".
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
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
//declaration
vector<int> powersOfTwo;
//adding members
powersOfTwo.push_back(1);
powersOfTwo.push_back(0);
powersOfTwo.push_back(4);
powersOfTwo.push_back(8);
//accessing
powersOfTwo[1] = 2;
4)
Structures in C++
Syntax
struct structureName {
//member declarations
};
Notes
Structures can be passed as function arguments (using the struct data type).
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;
}
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
//Memory allocation of the pointer of a specified size, usually of a certain data type
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
int x = 5;
int *pointer = &x; //referencing the memory address of x, and storing it in a pointer variable
cout << newPointer; //will print the address in the pointer variable
delete newPointer; //free the memory once done the operation on the variable
6)
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
Notes
A typedef is typically used to give a structure its own type, instead of having to type out 'struct
structName' every time.
Example
u_int myNumber;
//Is the same as doing this (except with a different variable name of course)
7)
Smart pointers are pointers that are deallocated for you, as opposed to having to make sure you 'delete'
or 'free' the pointer.
Syntax
Notes
Example
cout << newPointer; //will print the address in the pointer variable
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>
class Base
{
public:
Base(){
cout << "Base Constructor Called\n";
}
~Base(){
cout << "Base Destructor called\n";
}
};
int main()
{
Base *b = new Derived1();
delete b;
}
The above code output the following:
#include <iostream>
class Base
{
public:
Base(){
cout << "Base Constructor Called\n";
}
virtual ~Base(){
cout << "Base Destructor called\n";
}
};
int main()
{
Base *b = new Derived1();
delete b;
}
The output changed as following:
#include<iostream>
class base
public:
void show ()
public:
void print ()
void show ()
};
int main()
base *bptr;
derived d;
bptr = &d;
bptr->print();
bptr->show();
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.
// program
#include <bits/stdc++.h>
int main ()
char filename[100];
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"
// Convert string to const char * as system requires
cout << "Compiling file using " << command << endl;
system(command);
cout << "\nRunning file ";
system("./a.out");
return 0;
#include <iostream>
int main ()
system("pause");
return 0;
Run on IDE
Hello World!
#include <iostream>
#include <cstdlib>
int main ()
{
cout << "Hello World!" << endl;
cin.get(); // or getchar()
return 0;
Run on IDE
Hello World!
// system()
#include <iostream>
#include <cstdlib>
int main ()
if (system(NULL))
else
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.