C++ Interview Questions and Answers (2025)
Last Updated :
02 Jan, 2025
C++ – the must-known and all-time favourite programming language of coders. It is still relevant as it was in the mid-80s. As a general-purpose and object-oriented programming language is extensively employed mostly every time during coding. As a result, some job roles demand individuals be fluent in C++. It is utilized by top IT companies such as Evernote, LinkedIn, Microsoft, Opera, NASA, and Meta because of its dependability, performance, and wide range of settings in which it may be used. So, to get into these companies, you need to be thorough in these top 50 C++ interview questions which can make you seem like an expert in front of recruiters.
To make you interview-ready, we have brought the Top 50 C++ interview questions for beginner, intermediate and experienced which you must definitely go through in order to get yourself placed at top MNCs. The C++ Course includes a section dedicated to interview questions and answers, helping you get ready for your upcoming interviews with confidence.
C++ Interview Questions for Freshers
1. What is C++? What are the advantages of C++?
C++ is an object-oriented programming language that was introduced to overcome the jurisdictions where C was lacking. By object-oriented we mean that it works with the concept of polymorphism, inheritance, abstraction, encapsulation, object, and class.
Advantages of C++:
- C++ is an OOPs language that means the data is considered as objects.
- C++ is a multi-paradigm language; In simple terms, it means that we can program the logic, structure, and procedure of the program.
- Memory management is a key feature in C++ as it enables dynamic memory allocation
- It is a Mid-Level programming language which means it can develop games, desktop applications, drivers, and kernels
2. What are the different data types present in C++?
Following is the list of data types in C++:

Different types of data types in C++
3. Define ‘std’?
‘std’ is also known as Standard or it can be interpreted as a namespace. The command “using namespace std” informs the compiler to add everything under the std namespace and inculcate them in the global namespace. This all inculcation of global namespace benefits us to use “cout” and “cin” without using “std::_operator_”.
4. What are references in C++?
In C++, references are an alternative way to create an alias for another variable. A reference acts as a synonym for a variable, allowing you to access the variable directly without any additional syntax. They must be initialized when created and cannot be changed to refer to another variable afterward. This feature makes it easier to manipulate variables in functions while avoiding the overhead of copying large objects. A reference variable is preceded with a ‘&’ symbol.
Syntax:
int GFG = 10;
// reference variable
int& ref = GFG;
5. What do you mean by Call by Value and Call by Reference?
In this programming language to call a function we have 2 methods: Call by Value and Call by Reference
Call by Value
| Call by Reference
|
|---|
| A copy of a variable is passed. | A variable itself is passed fundamentally. |
| Calling a function by sending the values by copying variables. | Calling a function by sending the address of the passed variable. |
| The changes made in the function are never reflected outside the function on the variable. In short, the original value is never altered in Call by Value. | The changes made in the functions can be seen outside the function on the passed function. In short, the original value is altered in Call by reference. |
| Passed actual and formal parameters are stored in different memory locations. Therefore, making Call by Value a little memory insufficient | Passed actual and formal parameters are stored in the same memory location. Therefore, making Call by Reference a little more memory efficient. |
6. Define token in C++
A token is the smallest individual element of a program that is understood by a compiler. A token comprises the following:
- Keywords – That contain a special meaning to the compiler
- Identifiers – That hold a unique value/identity
- Constants – That never change their value throughout the program
- Strings – That contains the homogenous sequence of data
- Special Symbols – They have some special meaning and cannot be used for another purpose; eg: [] () {}, ; * = #
- Operators – Who perform operations on the operand
7. What is the difference between C and C++?
The following table lists the major differences between C and C++:
C
| C++
|
|---|
| It is a procedural programming language. In simple words, it does not support classes and objects | It is a mixture of both procedural and object-oriented programming languages. In simple words, it supports classes and objects. |
| It does not support any OOPs concepts like polymorphism, data abstraction, encapsulation, classes, and objects. | It supports all concepts of data |
| It does not support Function and Operator Overloading | It supports Function and Operator Overloading respectively |
| It is a function-driven language | It is an object-driven language |
8. What is the difference between struct and class?
Following table lists the primary difference between struct and class:
| Aspect | struct | class |
|---|
| Default Access Modifier | Members are public by default. | Members are private by default. |
|---|
| Memory Allocation | Can be allocated on the stack or heap. | Can be allocated on the stack or heap. |
|---|
| Inheritance | Supports inheritance (with public, protected, or private access). | Supports inheritance (with public, protected, or private access). |
|---|
| Use Case | Often used for Plain Old Data (POD) structures, or simple data grouping. | Suitable for complex objects that may include methods, constructors, and destructors. |
|---|
9. What is the difference between reference and pointer?
Following are the main difference between reference and pointer:
Reference
| Pointer
|
|---|
| The value of a reference cannot be reassigned | The value of a pointer can be reassigned |
| It can never hold a null value as it needs an existing value to become an alias of | It can hold or point at a null value and be termed as a nullptr or null pointer |
| It cannot work with arrays | It can work with arrays |
| To access the members of class/struct it uses a ‘ . ‘ | To access the members of class/struct it uses a ‘ -> ‘ |
| The memory location of reference can be accessed easily or it can be used directly | The memory location of a pointer cannot be accessed easily as we have to use a dereference ‘ * ‘ |
10. What is the difference between function overloading and operator overloading?
Following is the main difference operator overloading and function overloading:
Function Overloading
| Operator Overloading
|
|---|
| It is basically defining a function in numerous ways such that there are many ways to call it or in simple terms you have multiple versions of the same function | It is basically giving practice of giving a special meaning to the existing meaning of an operator or in simple terms redefining the pre-redefined meaning |
| Parameterized Functions are a good example of Function Overloading as just by changing the argument or parameter of a function you make it useful for different purposes | Polymorphism is a good example of an operator overloading as an object of allocations class can be used and called by different classes for different purposes |
Example of Function Overloading:
- int GFG(int X, int Y);
- int GFG(char X, char Y);
| Example of Operator Overloading:
- int GFG() = X() + Y();
- int GFG() = X() – Y();
|
11. What is the difference between an array and a list?
The major differences between the arrays and lists are:
Arrays
| Lists
|
|---|
| Array are contiguous memory locations of homogenous data types stored in a fixed location or size. | Lists are classic individual elements that are linked or connected to each other with the help of pointers and do not have a fixed size. |
| Arrays are static in nature. | Lists are dynamic in nature |
| Uses less memory than linked lists. | Uses more memory as it has to store the value and the pointer memory location |
12. What is the difference between a while loop and a do-while loop?
Following are the major difference between while and do-while loop:
While Loop
| do-while Loop
|
|---|
| While loop is also termed an entry-controlled loop | The do-while loop is termed an exit control loop |
| If the condition is not satisfied the statements inside the loop will not execute | Even if the condition is not satisfied the statements inside the loop will execute for at least one time |
Example of a while loop:
while(condition)
{statements to be executed;};
| Example of a do-while loop:
do {
statements to be executed;
} while(condition or expression);
|
13. Discuss the difference between prefix and postfix?
Following are the major difference between prefix and postfix:
prefix
| postfix
|
|---|
| It simply means putting the operator before the operand | It simply means putting the operator after the operand |
| It executes itself before ‘; ‘ | It executes itself after ‘; ‘ |
| Associativity of prefix ++ is right to left | Associativity of postfix ++ is left to right |
14. What is the difference between new and malloc()?
Following are the major difference between new and malloc()
new
| malloc()
|
|---|
| new is an operator which performs an operation | malloc is a function that returns and accepts values |
| new calls the constructors | malloc cannot call a constructor |
| new is faster than malloc as it is an operator | malloc is slower than new as it is a function |
| new returns the exact data type | malloc returns void* |
15. What is the difference between virtual functions and pure virtual functions?
Following are the major difference between virtual functions and pure virtual functions
Virtual Function
| Pure Virtual Function
|
|---|
| A Virtual Function is a member function of a base class that can be redefined in another derived class. | A Pure Virtual Function is a member function of a base class that is only declared in a base class and defined in a derived class to prevent it from becoming an abstract class. |
| A virtual Function has its definition in its respective base class. | There is no definition in Pure Virtual Function and is initialized with a pure specifier (= 0). |
| The base class has a virtual function that can be represented or instanced; In simple words, its object can be made. | A base class having pure virtual function becomes abstract that cannot be represented or instanced; In simple words, it means its object cannot be made. |
16. What are classes and objects in C++?
A class is a user-defined data type where all the member functions and data members are tailor-made according to demands and requirements in addition to which these all can be accessed with the help of an object. To declare a user-defined data type we use a keyword class.
An object is an instance of a class and an entity with value and state; In simple terms, it is used as a catalyst or to represent a class member. It may contain different parameters or none.
Note: A class is a blueprint that defines functions which are used by an object.
17. What is Function Overriding?
When a function of the same name, same arguments or parameters, and same return type already present/declared in the base class is used in a derived class is known as Function Overriding. It is an example of Runtime Polymorphism or Late Binding which means the overridden function will be executed at the run time of the execution.
18. What are the various OOPs concepts in C++?
Following are the OOPs concepts in C++:
- Classes: It is a user-defined datatype
- Objects: It is an instance of a class
- Abstraction: It is a technique of showing only necessary details
- Encapsulation: Wrapping of data in a single unit
- Inheritance: The capability of a class to derive properties and characteristics from another class
- Polymorphism: Polymorphism is known as many forms of the same thing
19. Explain inheritance
The capability or ability of a class to derive properties and characteristics from another class is known as inheritance. In simple terms, it is a system or technique of reusing and extending existing classes without modifying them.
20. When should we use multiple inheritance?
Multiple inheritances mean that a derived class can inherit two or more base/parent classes. It is useful when a derived class needs to combine numerous attributes/contracts and inherit some, or all, of the implementation from these attributes/contracts. To take a real-life example consider your Parents where Parent A is your DAD Parent B is your MOM and Chid C is you.

Multiple Inheritances
21. What is virtual inheritance?
Virtual inheritance is a technique that ensures only one copy of a base class’s member variables is inherited by grandchild-derived classes. Or in simple terms, virtual inheritance is used when we are dealing with a situation of multiple inheritances but want to prevent multiple instances of the same class from appearing in the inheritance hierarchy.
22. What is polymorphism in C++?
Polymorphism is known as many forms of the same thing. In simple terms, we can say that Polymorphism is the ability to display a member function in multiple forms depending on the type of object that calls them.
In other words, we can also say that a man can be an employee to someone, a son of someone, a father of someone, and a husband of someone; this is how polymorphism can be projected in real life.
There is 2 type of polymorphism:
- Compile Time Polymorphism
- Function Overloading
- Operator Overloading
- Run Time Polymorphism
- Function Overriding
- Virtual Function
23. What are the different types of polymorphism in C++?
There is 2 type of polymorphism
Compile Time Polymorphism or Static Binding
This type of polymorphism is achieved during the compile time of the program which results in it making a bit faster than Run time. Also, Inheritance is not involved in it. It is comprised of 2 further techniques:
Function Overloading: When there are multiple functions with the same name but different parameters then this is known as function overloading.
C++
// same name different arguments
int GFG() {}
int GFG(int a) {}
float GFG(double a) {}
int GFG(int a, double b) {}
Operator Overloading: It is basically giving practice of giving a special meaning to the existing meaning of an operator or in simple terms redefining the pre-redefined meaning
C++
class GFG {
// private and other modes
statements public returnType
operator symbol(arguments){ statements } statements
};
Run-Time Polymorphism or Late Binding
Run-time polymorphism takes place when functions are invoked during run time.
Function Overriding: Function overriding occurs when a base class member function is redefined in a derived class with the same arguments and return type.
C++
// C++ program to demonstrate
// Function overriding
#include
<iostream> using namespace std;
class GFG {
public:
virtual void display()
{
cout << "Function of base class" << endl;
}
};
class derived_GFG : public GFG {
public:
void display()
{
cout << "Function of derived class" << endl;
}
};
int main()
{
derived_GFG dg;
dg.display();
return 0;
}
Output:
Function of derived class
24. Compare compile-time polymorphism and Runtime polymorphism
Following are the major differences between the runtime and compile time polymorphism:
Compile-Time Polymorphism
| Runtime Polymorphism
|
|---|
| It is also termed static binding and early binding. | It is also termed Dynamic binding and Late binding. |
| It is fast because execution is known early at compile time. | It is slow as compared to compile-time because execution is known at runtime. |
| It is achieved by function overloading and operator overloading. | It is achieved by virtual functions and function overriding. |
25. Explain the constructor in C++.
A constructor is a special type of member function of a class, whose name is the same as that of the class by whom it is invoked and initializes value to the object of a class.
There are 3 types of constructors:
A. Default constructor: It is the most basic type of constructor which accepts no arguments or parameters. Even if it is not called the compiler calls it automatically when an object is created.
Example:
C++
class Class_name {
public:
Class_name() { cout << "I am a default constructor"; }
};
B. Parameterized constructor: It is a type of constructor which accepts arguments or parameters. It has to be called explicitly by passing values in the arguments as these arguments help initialize an object when it is created. It also has the same name as that of the class.
Also, It is used to overload constructors.
Example:
C++
// CPP program to demonstrate
// parameterized constructors
#include
<iostream> using namespace std;
class GFG {
private:
int x, y;
public:
// Parameterized Constructor
GFG(int x1, int y1)
{
x = x1;
y = y1;
}
int getX() { return x; }
int getY() { return y; }
};
int main()
{
// Constructor called
GFG G(10, 15);
// Access values assigned by constructor
cout << "G.x = " << G.getX() << ", G.y = " << G.getY();
return 0;
}
Output
G.x = 10, G.y = 15
C. Copy Constructor: A copy constructor is a member function that initializes an object using another object of the same class. Also, the Copy constructor takes a reference to an object of the same class as an argument.
Example:
C++
Sample(Sample& t) { id = t.id; }
26. What are destructors in C++?
Destructors are members of functions in a class that delete an object when an object of the class goes out of scope. Destructors have the same name as the class preceded by a tilde (~) sign. Also, destructors follow a down-to-top approach, unlike constructors which follow a top-to-down.
Syntax:
~constructor_name(); // tilde sign signifies that it is a destructor
27. What is a virtual destructor?
When destroying instances or objects of a derived class using a base class pointer object, a virtual destructor is invoked to free up memory space allocated by the derived class object or instance.
Virtual destructor guarantees that first the derived class’ destructor is called. Then the base class’s destructor is called to release the space occupied by both destructors in the inheritance class which saves us from the memory leak. It is advised to make your destructor virtual whenever your class is polymorphic.
28. Is destructor overloading possible? If yes then explain and if no then why?
The simple answer is NO we cannot overload a destructor. It is mandatory to only destructor per class in C++. Also to mention, Destructor neither take arguments nor they have a parameter that might help to overload.

C++ Interview Questions – Intermediate Level
29. Which operations are permitted on pointers?
Pointers are the variables that are used to store the address location of another variable. Operations that are permitted to a pointer are:
- Increment/Decrement of a Pointer
- Addition and Subtraction of integer to a pointer
- Comparison of pointers of the same type
30. What is the purpose of the “delete” operator?
The delete operator is used to delete/remove all the characteristics/properties from an object by deallocating its memory; furthermore, it returns true or false in the end. In simple terms, it destroys or deallocates array and non-array(pointer) objects which are created by new expressions.
C++
int GFG = new int[100];
// uses GFG for deletion
delete[] GFG;
31. How delete [] is different from delete?
delete[]
| delete
|
|---|
| It is used for deleting a whole array | It is used to delete only one single pointer |
| It is used for deleting the objects of new[]; By this, we can say that delete[] is used to delete an array of objects | It is used for deleting the objects of new; By this, we can say that delete is used to delete a single object |
| It can call as many destructors it wants | It can only call the destructor of a class once |
32. What do you know about friend class and friend function?
A friend class is a class that can access both the protected and private variables of the classes where it is declared as a friend.
Example of friend class:
C++
class Class_1st {
// ClassB is a friend class of ClassA
friend class Class_2nd;
statements;
} class Class_2nd {
statements;
}
A friend function is a function used to access the private, protected, and public data members or member functions of other classes. It is declared with a friend keyword. The advantage of a friend function is that it is not bound to the scope of the class and once it is declared in a class, furthermore to that, it cannot be called by an object of the class; therefore it can be called by other functions. Considering all the mentioned points we can say that a friend function is a global function.
Example of friend function:
C++
class GFG {
statements;
friend dataype function_Name(arguments);
statements;
} OR class GFG {
statements' friend int divide(10, 5);
statements;
}
33. What is an Overflow Error?
Overflow Error occurs when the number is too large for the data type to handle. In simple terms, it is a type of error that is valid for the defined but exceeds used the defined range where it should coincide/lie.
For example, the range of int data type is –2,147,483,648 to 2,147,483,647 and if we declare a variable of size 2,247,483,648 it will generate a overflow error.
34. What does the Scope Resolution operator do?
A scope resolution operator is denoted by a ‘::‘ symbol. Just like its name this operator resolves the barrier of scope in a program. A scope resolution operator is used to reference a member function or a global variable out of their scope furthermore to which it can also access the concealed variable or function in a program.
Scope Resolution is used for numerous amounts of tasks:
- To access a global variable when there is a local variable with the same name
- To define the function outside the class
- In case of multiple inheritances
- For namespace
35. What are the C++ access modifiers?
The access restriction specified to the class members (whether it is member function or data member) is known as access modifiers/specifiers.
Access Modifiers are of 3 types:
- Private – It can neither be accessed nor be viewed from outside the class
- Protected – It can be accessed if and only if the accessor is the derived class
- Public – It can be accessed or be viewed from outside the class
36. Can you compile a program without the main function?
Yes, it is absolutely possible to compile a program without a main(). For example Use Macros that defines the main
C++
// C++ program to demonstrate the
// a program without main()
#include
<stdio.h>
#define fun main
int fun(void)
{
printf("Geeksforgeeks");
return 0;
}
37. What is STL?
STL is known as Standard Template Library, it is a library that provides 4 components like container, algorithms, and iterators.

C++ STL
38. Define inline function. Can we have a recursive inline function in C++?
An inline function is a form of request not an order to a compiler which results in the inlining of our function to the main function body. An inline function can become overhead if the execution time of the function is less than the switching time from the caller function to called function. To make a function inline use the keyword inline before and define the function before any calls are made to the function.

Inline Function Explanation
Syntax:
inline data_type function_name()
{
Body;
}The answer is No; It cannot be recursive.
An inline function cannot be recursive because in the case of an inline function the code is merely placed into the position from where it is called and does not maintain a piece of information on the stack which is necessary for recursion.
Plus, if you write an inline keyword in front of a recursive function, the compiler will automatically ignore it because the inline is only taken as a suggestion by the compiler.
39. What is an abstract class and when do you use it?
An abstract class is a class that is specifically designed to be used as a base class. An abstract class contains at least one pure virtual function. You declare a pure virtual function by using a pure specifier(= 0) in the declaration of a virtual member function in the class declaration
You cannot use an abstract class as a parameter type, a function return type, or the type of an explicit conversion, nor can you declare an object of an abstract class. However, it can be used to declare pointers and references to an abstract class.
An abstract class is used if you want to provide a common, implemented functionality among all the implementations of the component. Abstract classes will allow you to partially implement your class, whereas interfaces would have no implementation for any members whatsoever. In simple words, Abstract Classes are a good fit if you want to provide implementation details to your children but don’t want to allow an instance of your class to be directly instantiated.
40. What are the static data members and static member functions?
The static data member of a class is a normal data member but preceded with a static keyword. It executes before main() in a program and is initialized to 0 when the first object of the class is created. It is only visible to a defined class but its scope is of a lifetime.
Syntax:
static Data_Type Data_Member;
The static member function is the member function that is used to access other static data members or other static member functions. It is also defined with a static keyword. We can access the static member function using the class name or class objects.
Syntax:
classname::function name(parameter);
C++ Interview Questions – Expert Level
41. What is the main use of the keyword “Volatile”?
Just like its name, things can change suddenly and unexpectantly; So it is used to inform the compiler that the value may change anytime. Also, the volatile keyword prevents the compiler from performing optimization on the code. It was intended to be used when interfacing with memory-mapped hardware, signal handlers, and machine code instruction.
42. Define storage class in C++ and name some
Storage class is used to define the features(lifetime and visibility) of a variable or function. These features usually help in tracing the existence of a variable during the runtime of a program.
Syntax:
storage_class var_data_type var_name;
Some types of storage classes:

Examples of storage class
43. What is a mutable storage class specifier? How can they be used?
Just like its name, the mutable storage class specifier is used only on a class data member to make it modifiable even though the member is part of an object declared as const. Static or const, or reference members cannot use the mutable specifier. When we declare a function as const, this pointer passed to the function becomes const.
44. Define the Block scope variable.
So the scope of a variable is a region where a variable is accessible. There are two scope regions, A global and block or local.
A block scope variable is also known as a local scope variable. A variable that is defined inside a function (like main) or inside a block (like loops and if blocks) is a local variable. It can be used ONLY inside that particular function/block in which it is declared. a block-scoped variable will not be available outside the block even if the block is inside a function.
45. What is the function of the keyword “Auto”?
The auto keyword may be used to declare a variable with a complex type in a straightforward fashion. You can use auto to declare a variable if the initialization phrase contains templates, pointers to functions, references to members, etc. With type inference capabilities, we can spend less time having to write out things the compiler already knows. As all the types are deduced in the compiler phase only, the time for compilation increases slightly but it does not affect the runtime of the program.
46. Define namespace in C++.
Namespaces enable us to organize named items that would otherwise have global scope into smaller scopes, allowing us to give them namespace scope. This permits program parts to be organized into distinct logical scopes with names. The namespace provides a place to define or declare identifiers such as variables, methods, and classes.
Or we could say that A namespace is a declarative zone that gives the identifiers (names of types, functions, variables, and so on) within it a scope. Namespaces are used to arrange code into logical categories and to avoid name clashes, which might happen when you have many libraries in your code base.
47. When is void() return type used?
The void keyword, when used as a function return type, indicates that the function does not return a value. When used as a parameter list for a function, void indicates that the function takes no parameters. Non-Value Returning functions are also known as void functions. They’re called “void” since they’re not designed to return anything. True, but only partially. We can’t return values from void functions, but we can certainly return something. Although void functions have no return type, they can return values.
48. What is the difference between shallow copy and deep copy?
Following are the primary differences between the shallow copy VS deep copy:
Shallow Copy
| Deep Copy
|
|---|
| In Shallow copy, a copy of the original object is stored and only the reference address is finally copied. In simple terms, Shallow copy duplicates as little as possible | In Deep copy, the copy of the original object and the repetitive copies both are stored. In simple terms, Deep copy duplicates everything |
| A shallow copy of a collection is a copy of the collection structure, not the elements. With a shallow copy, two collections now share individual elements. | A deep copy of a collection is two collections with all of the elements in the original collection duplicated. |
| A shallow copy is faster | Deep copy is comparatively slower. |
49. Can we call a virtual function from a constructor?
Yes, we can call a virtual function from a constructor. But it can throw an exception of overriding.
50. What are void pointers?
Just like its name a void pointer is a pointer that is not associated with anything or with any data type. Nevertheless, a void pointer can hold the address value of any type and can be converted from one data type to another.
Bonus Question:
What is ‘this‘ pointer in C++?
this pointer enables every object to have access to its own address through an essential pointer. All member functions take this pointer as an implicit argument. this pointer may be used to refer to the calling object within a member function.
- this pointer is used to pass an object as a parameter to another method.
- Each object gets its own copy of the data member.
- this pointer is used to declare indexers.
Similar Reads
C++ Programming Language
C++ is a programming language that is the foundation of many modern technologies like game engines, web browsers, operating systems financial systems, etc. Bjarne Stroustrup developed it as an extension of the C language. C++ is generally used to create high-performance applications and provides bet
9 min read
C++ Overview
Introduction to C++ Programming Language
C++ is a general-purpose programming language that was developed as an enhancement of the C language to include object-oriented paradigm. It is an imperative and a compiled language. C++ is a high-level, general-purpose programming language designed for system and application programming. It was dev
7 min read
Features of C++
C++ is a general-purpose programming language that was developed as an enhancement of the C language to include an object-oriented paradigm. It is an imperative and compiled language. C++ has a number of features, including: Object-Oriented ProgrammingMachine IndependentSimpleHigh-Level LanguagePopu
6 min read
History of C++
The C++ language is an object-oriented programming language & is a combination of both low-level & high-level language - a Middle-Level Language. The programming language was created, designed & developed by a Danish Computer Scientist - Bjarne Stroustrup at Bell Telephone Laboratories (
7 min read
Interesting Facts about C++
C++ is a general-purpose, object-oriented programming language. It supports generic programming and low-level memory manipulation. Bjarne Stroustrup (Bell Labs) in 1979, introduced the C-With-Classes, and in 1983 with the C++. Here are some awesome facts about C++ that may interest you: The name of
2 min read
Setting up C++ Development Environment
C++ is a general-purpose programming language and is widely used nowadays for competitive programming. It has imperative, object-oriented, and generic programming features. C++ runs on lots of platforms like Windows, Linux, Unix, Mac, etc. Before we start programming with C++. We will need an enviro
8 min read
Difference between C and C++
C++ is often viewed as a superset of C. C++ is also known as a "C with class" This was very nearly true when C++ was originally created, but the two languages have evolved over time with C picking up a number of features that either weren't found in the contemporary version of C++ or still haven't m
4 min read
C++ Variables and Constants
C++ Variables
In C++, variable is a name given to a memory location. It is the basic unit of storage in a program. The value stored in a variable can be accessed or changed during program execution. In this article, we will learn about the variables in C++ and how to use them in our programs. Let's take a look at
4 min read
Constants in C
The constants in C are the read-only variables whose values cannot be modified once they are declared in the C program. The type of constant can be an integer constant, a floating pointer constant, a string constant, or a character constant. In C language, the const keyword is used to define the con
6 min read
Scope of Variables in C++
In C++, the scope of a variable is the extent in the code upto which the variable can be accessed or worked with. It is the region of the program where the variable is accessible using the name it was declared with. Let's take a look at an example: [GFGTABS] C++ #include <iostream> using names
7 min read
Storage Classes in C++ with Examples
C++ Storage Classes are used to describe the characteristics of a variable/function. It determines the lifetime, visibility, default value, and storage location which helps us to trace the existence of a particular variable during the runtime of a program. Storage class specifiers are used to specif
7 min read
Static Keyword in C++
The static keyword in C++ has different meanings when used with different types. In this article, we will learn about the static keyword in C++ along with its various uses. In C++, a static keyword can be used in the following context: Table of Content Static Variables in a FunctionStatic Member Var
6 min read
C++ Data Types and Literals
C++ Data Types
Data types specify the type of data that a variable can store. Whenever a variable is defined in C++, the compiler allocates some memory for that variable based on the data type with which it is declared as every data type requires a different amount of memory. C++ supports a wide variety of data ty
6 min read
Literals in C
In C, Literals are the constant values that are assigned to the variables. Literals represent fixed values that cannot be modified. Literals contain memory but they do not have references as variables. Generally, both terms, constants, and literals are used interchangeably. For example, “const int =
4 min read
Derived Data Types in C++
The data types that are derived from the primitive or built-in datatypes are referred to as Derived Data Types. They are generally the data types that are created from the primitive data types and provide some additional functionality. In C++, there are four different derived data types: Table of Co
4 min read
User Defined Data Types in C++
User defined data types are those data types that are defined by the user himself. In C++, these data types allow programmers to extend the basic data types provided and create new types that are more suited to their specific needs. C++ supports 5 user-defined data types: Table of Content ClassStruc
4 min read
Data Type Ranges and Their Macros in C++
Most of the times, in competitive programming, there is a need to assign the variable, the maximum or minimum value that data type can hold but remembering such a large and precise number comes out to be a difficult job. Therefore, C++ has certain macros to represent these numbers, so that these can
4 min read
C++ Type Modifiers
In C++, type modifiers are the keywords used to change or give extra meaning to already existing data types. It is added to primitive data types as a prefix to modify their size or range of data they can store. C++ have 4 type modifiers which are as follows: Table of Content signed Modifierunsigned
4 min read
Type Conversion in C++
Type conversion means converting one type of data to another compatible type such that it doesn't lose its meaning. It is essential for managing different data types in C++. Let's take a look at an example: [GFGTABS] C++ #include <iostream> using namespace std; int main() { // Two variables of
4 min read
Casting Operators in C++
The casting operators the modern C++ solution for converting one type of data safely to another type. This process is called typecasting where the type of the data is changed to another type either implicitly (by the compiler) or explicitly (by the programmer). Let's take a look at an example: [GFGT
5 min read
C++ Operators
Operators in C++
An operator is a symbol that operates on a value to perform specific mathematical or logical computations. They form the foundation of any programming language. In C++, we have built-in operators to provide the required functionality. An operator operates the operands. For example, int c = a + b;He
13 min read
C++ Arithmetic Operators
Arithmetic Operators in C++ are used to perform arithmetic or mathematical operations on the operands (generally numeric values). An operand can be a variable or a value. For example, ‘+’ is used for addition, '-' is used for subtraction, '*' is used for multiplication, etc. Let's take a look at an
4 min read
Unary operators in C
Unary operators are the operators that perform operations on a single operand to produce a new value. Types of unary operatorsTypes of unary operators are mentioned below: Unary minus ( - )Increment ( ++ )Decrement ( -- )NOT ( ! )Addressof operator ( & )sizeof()1. Unary MinusThe minus operator (
5 min read
Bitwise Operators in C
In C, the following 6 operators are bitwise operators (also known as bit operators as they work at the bit-level). They are used to perform bitwise operations in C. The & (bitwise AND) in C takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if bot
7 min read
Assignment Operators in C
Assignment operators are used for assigning value to a variable. The left side operand of the assignment operator is a variable and right side operand of the assignment operator is a value. The value on the right side must be of the same data-type of the variable on the left side otherwise the compi
3 min read
C++ sizeof Operator
The sizeof operator is a unary compile-time operator used to determine the size of variables, data types, and constants in bytes at compile time. It can also determine the size of classes, structures, and unions. Let's take a look at an example: [GFGTABS] C++ #include <iostream> using namespac
3 min read
Scope Resolution Operator in C++
In C++, the scope resolution operator (::) is used to access the identifiers such as variable names and function names defined inside some other scope in the current scope. Let's take a look at an example: [GFGTABS] C++ #include <iostream> int main() { // Accessing cout from std namespace usin
3 min read
C++ Control Statements
Decision Making in C (if , if..else, Nested if, if-else-if )
The conditional statements (also known as decision control structures) such as if, if else, switch, etc. are used for decision-making purposes in C programs. They are also known as Decision-Making Statements and are used to evaluate one or more conditions and make the decision whether to execute a s
11 min read
C++ if Statement
The C++ if statement is the most simple decision-making statement. It is used to decide whether a certain statement or block of statements will be executed or not executed based on a certain condition. Let's take a look at an example: [GFGTABS] C++ #include <iostream> using namespace std; int
3 min read
C++ if else Statement
The if statement alone tells us that if a condition is true it will execute a block of statements and if the condition is false, it won’t. But what if we want to do something else if the condition is false. Here comes the C++ if else statement. We can use the else statement with if statement to exec
4 min read
C++ if else if Ladder
In C++, the if-else-if ladder helps the user decide from among multiple options. The 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. I
3 min read
Switch Statement in C++
In C++, the switch statement is a flow control statement that is used to execute the different blocks of statements based on the value of the given expression. It is an alternative to the long if-else-if ladder which provides an easy way to execute different parts of code based on the value of the e
7 min read
Jump statements in C++
Jump statements are used to manipulate the flow of the program if some conditions are met. It is used to terminate or continue the loop inside a program or to stop the execution of a function. In C++, there is four jump statement: Table of Content continue Statementbreak Statementreturn Statementgot
4 min read
C++ Loops
In Programming, sometimes there is a need to perform some operation more than once or (say) n number of times. Loops come into use when we need to repeatedly execute a block of statements. For example: Suppose we want to print "Hello World" 10 times. This can be done in two ways as shown below: Ma
13 min read
for Loop in C++
In C++, for loop is an entry-controlled loop that is used to execute a block of code repeatedly for the given number of times. It is generally preferred over while and do-while loops in case the number of iterations is known beforehand. Let's take a look at an example: [GFGTABS] C++ #include <bit
6 min read
Range-Based for Loop in C++
In C++, the range-based for loop introduced in C++ 11 is a version of for loop that is able to iterate over a range. This range can be anything that is iteratable, such as arrays, strings and STL containers. It provides a more readable and concise syntax compared to traditional for loops. Let's take
4 min read
C++ While Loop
In C++, the while loop is an entry-controlled loop that repeatedly executes a block of code as long as the given condition remains true. Unlike the for loop, while loop is used in situations where we do not know the exact number of iterations of the loop beforehand as the loop execution is terminate
3 min read
C++ do while Loop
In C++, the do-while loop is an exit-controlled loop that repeatedly executes a block of code at least once and continues executing as long as a given condition remains true. Unlike the while loop, the do-while loop guarantees that the loop body will execute at least once, regardless of whether the
4 min read
C++ Pointers and References
Pointers and References in C++
In C++ pointers and references both are mechanisms used to deal with memory, memory address, and data in a program. Pointers are used to store the memory address of another variable whereas references are used to create an alias for an already existing variable. Pointers in C++ Pointers in C++ are a
5 min read
C++ Pointers
Pointers are symbolic representations of addresses. They enable programs to simulate call-by-reference as well as to create and manipulate dynamic data structures. Iterating over elements in arrays or other data structures is one of the main use of pointers. The address of the variable you're workin
9 min read
Dangling, Void , Null and Wild Pointers in C
In C programming pointers are used to manipulate memory addresses, to store the address of some variable or memory location. But certain situations and characteristics related to pointers become challenging in terms of memory safety and program behavior these include Dangling (when pointing to deall
6 min read
Applications of Pointers in C
Pointers in C are variables that are used to store the memory address of another variable. Pointers allow us to efficiently manage the memory and hence optimize our program. In this article, we will discuss some of the major applications of pointers in C. Prerequisite: Pointers in C. C Pointers Appl
4 min read
Understanding nullptr in C++
Consider the following C++ program that shows problem with NULL (need of nullptr) [GFGTABS] CPP // C++ program to demonstrate problem with NULL #include <bits/stdc++.h> using namespace std; // function with integer argument void fun(int N) { cout << "fun(int)"; return;} // Over
3 min read
References in C++
When a variable is declared as a reference, it becomes an alternative name for an existing variable. A variable can be declared as a reference by putting ‘&’ in the declaration. Also, we can define a reference variable as a type of variable that can act as a reference to another variable. '&
9 min read
Can References Refer to Invalid Location in C++?
Reference Variables: You can create a second name for a variable in C++, which you can use to read or edit the original data contained in that variable. While this may not sound appealing at first, declaring a reference and assigning it a variable allows you to treat the reference as if it were the
2 min read
Pointers vs References in C++
Prerequisite: Pointers, References C and C++ support pointers, which is different from most other programming languages such as Java, Python, Ruby, Perl and PHP as they only support references. But interestingly, C++, along with pointers, also supports references. On the surface, both references and
5 min read
Passing By Pointer vs Passing By Reference in C++
In C++, we can pass parameters to a function either by pointers or by reference. In both cases, we get the same result. So, what is the difference between Passing by Pointer and Passing by Reference in C++? Let's first understand what Passing by Pointer and Passing by Reference in C++ mean: Passing
5 min read
When do we pass arguments by pointer?
In C, the pass-by pointer method allows users to pass the address of an argument to the function instead of the actual value. This allows programmers to change the actual data from the function and also improve the performance of the program. In C, variables are passed by pointer in the following ca
5 min read
C++ Strings
Strings in C++
C++ strings are sequences of characters stored in a char array. Strings are used to store words and text. They are also used to store data, such as numbers and other types of information. Strings in C++ can be defined either using the std::string class or the C-style character arrays. 1. C Style Str
11 min read
std::string class in C++
C++ has in its definition a way to represent a sequence of characters as an object of the class. This class is called std:: string. The string class stores the characters as a sequence of bytes with the functionality of allowing access to the single-byte character. String vs Character ArrayString Ch
8 min read
Array of Strings in C++ - 5 Different Ways to Create
In C++, a string is usually just an array of (or a reference/points to) characters that ends with the NULL character '\0'. A string is a 1-dimensional array of characters, and an array of strings is a 2-dimensional array of characters where each row contains some string. In this article, we will dis
6 min read
String Concatenation in C++
String concatenation refers to the process of combining two or more strings into a single string. Generally, one string is appended at the end of the other string. In this article, we will learn how to concatenate two strings in C++. The simplest method to concatenate two strings in C++ is by using
3 min read
Tokenizing a string in C++
Tokenizing a string denotes splitting a string with respect to some delimiter(s). There are many ways to tokenize a string. The C++ Course covers methods for tokenizing strings effectively, helping you manipulate and analyze text data in your applications. In this article four of them are explained:
4 min read
Substring in C++
The substring function is used for handling string operations like strcat(), append(), etc. It generates a new string with its value initialized to a copy of a sub-string of this object. In C++, the header file which is required for std::substr(), string functions is <string>. The substring fu
8 min read
C++ Structures and Unions
Structures, Unions and Enumerations in C++
In this article, we will discuss structures, unions, and enumerations and their differences. The structure is a user-defined data type that is available in C++.Structures are used to combine different types of data types, just like an array is used to combine the same type of data types.A structure
5 min read
Structures in C++
We often come around situations where we need to store a group of data whether of similar data types or non-similar data types. We have seen Arrays in C++ which are used to store set of data of similar data types at contiguous memory locations.Unlike Arrays, Structures in C++ are user defined data t
5 min read
C++ - Pointer to Structure
Pointer to structure in C++ can also be referred to as Structure Pointer. A structure Pointer in C++ is defined as the pointer which points to the address of the memory block that stores a structure. Below is an example of the same: Syntax: struct name_of_structure *ptr; // Initialization of structu
2 min read
Self Referential Structures
Self Referential structures are those structures that have one or more pointers which point to the same type of structure, as their member. In other words, structures pointing to the same type of structures are self-referential in nature Example: [GFGTABS] CPP struct node { int data1; char data2; s
8 min read
Difference Between C Structures and C++ Structures
Let's discuss, what are the differences between structures in C and structures in C++? In C++, structures are similar to classes. Differences Between the C and C++ StructuresC Structures C++ Structures Only data members are allowed, it cannot have member functions.Can hold both: member functions and
6 min read
Enumeration in C++
Enumeration (Enumerated type) is a user-defined data type that can be assigned some limited values. These values are defined by the programmer at the time of declaring the enumerated type. If we assign a float value to a character value, then the compiler generates an error. In the same way, if we t
3 min read
typedef in C++
typedef keyword in C++ is used for aliasing existing data types, user-defined data types, and pointers to a more meaningful name. Typedefs allow you to give descriptive names to standard data types, which can also help you self-document your code. Mostly typedefs are used for aliasing, only if the p
6 min read
Array of Structures vs Array within a Structure in C
Both Array of Structures and Array within a Structure in C programming is a combination of arrays and structures but both are used to serve different purposes. Array within a StructureA structure is a data type in C that allows a group of related variables to be treated as a single unit instead of s
5 min read
C++ Dynamic Memory Management
C++ Object-Oriented Programming
Object Oriented Programming in C++
Object-oriented programming - As the name suggests uses objects in programming. Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc. in programming. The main aim of OOP is to bind together the data and the functions that operate on them so th
10 min read
C++ Classes and Objects
In C++, classes and objects are the basic building block that leads to Object-Oriented programming in C++. In this article, we will learn about C++ classes, objects, look at how they work and how to implement them in our C++ program. What is a Class in C++?A class is a user-defined data type, which
10 min read
Access Modifiers in C++
Access modifiers are used to implement an important aspect of Object-Oriented Programming known as Data Hiding. Consider a real-life example: The Research and Analysis Wing (R&AW), having 10 core members, has come into possession of sensitive confidential information regarding national security.
6 min read
Friend Class and Function in C++
A friend class can access private and protected members of other classes in which it is declared as a friend. It is sometimes useful to allow a particular class to access private and protected members of other classes. For example, a LinkedList class may be allowed to access private members of Node.
6 min read
Constructors in C++
Constructor in C++ is a special method that is invoked automatically at the time an object of a class is created. It is used to initialize the data members of new objects generally. The constructor in C++ has the same name as the class or structure. It constructs the values i.e. provides data for th
7 min read
Default Constructors in C++
A default constructor is a constructor that either takes no arguments or has default values for all its parameters. It is also referred to as a zero-argument constructor when it explicitly accepts no arguments. If a default constructor is not explicitly defined by the programmer in the source code,
4 min read
Copy Constructor in C++
A copy constructor is a type of constructor that initializes an object using another object of the same class. In simple terms, a constructor which creates an object by initializing it with an object of the same class, which has been created previously is known as a copy constructor. The process of
7 min read
Destructors in C++
Destructor is an instance member function that 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. In this article, we will learn about the destructors in C++, how they work, how an
5 min read
Private Destructor in C++
Destructors with the access modifier as private are known as Private Destructors. Whenever we want to prevent the destruction of an object, we can make the destructor private. What is the use of private destructor? Whenever we want to control the destruction of objects of a class, we make the destru
4 min read
When is a Copy Constructor Called in C++?
A copy constructor is a member function that initializes an object using another object of the same class. The Copy constructor is called mainly when a new object is created from an existing object, as a copy of the existing object. In C++, a Copy Constructor may be called for the following cases: 1
2 min read
Shallow Copy and Deep Copy in C++
In general, creating a copy of an object means to create an exact replica of the object having the same literal value, data type, and resources. There are two ways that are used by C++ compiler to create a copy of objects. Copy ConstructorAssignment Operator// Copy ConstructorGeeks Obj1(Obj);orGeeks
6 min read
When Should We Write Our Own Copy Constructor in C++?
A copy constructor is a member function that initializes an object using another object of the same class. (See this article for reference). When should we write our own copy constructor?C++ compiler provides a default copy constructor (and assignment operator) with class. When we don't provide an i
2 min read
Does C++ compiler create default constructor when we write our own?
No, the C++ compiler doesn't create a default constructor when we define any type of constructor manually in the class. ExplanationThe default constructor is used to create an object's instance without any arguments. In C++, the compiler implicitly creates a default constructor for every class which
2 min read
C++ Static Data Members
Static data members are class members that are declared using static keywords. A static member has certain special characteristics which are as follows: Only one copy of that member is created for the entire class and is shared by all the objects of that class, no matter how many objects are created
6 min read
Static Member Function in C++
The static keyword is used with a variable to make the memory of the variable static once a static variable is declared its memory can't be changed. To know more about static keywords refer to the article static Keyword in C++. Static Member in C++ Static members of a class are not associated with t
4 min read
'this' pointer in C++
In C++, 'this' pointers is a pointer to the current instance of a class. It is used to refer to the object within its own member functions. In this article, we will learn how to use 'this' pointer in C++. Let's take a look at an example: [GFGTABS] C++ #include <iostream> using namespace std; /
6 min read
Scope Resolution Operator vs this pointer in C++
Scope resolution operator is for accessing static or class members and this pointer is for accessing object members when there is a local variable with the same name. Consider below C++ program: C/C++ Code // C++ program to show that local parameters hide // class members #include <iostream> u
3 min read
Local Classes in C++
A class declared inside a function becomes local to that function and is called Local Class in C++. A local class name can only be used locally i.e., inside the function and not outside it.The methods of a local class must be defined inside it only.A local class can have static functions but, not st
6 min read
Nested Classes in C++
A nested class is a class which is declared in another enclosing class. A nested class is a member and as such has the same access rights as any other member. The members of an enclosing class have no special access to members of a nested class; the usual access rules shall be obeyed. For example, p
1 min read
Enum Classes in C++ and Their Advantage over Enum DataType
Enums, or enumerated types, are user-defined data types in C++ that allow the programmer to define a set of named values. These values are fixed and predetermined at the time of declaration. However, traditional enums have some limitations, which have been addressed by the introduction of Enum Class
5 min read
Difference Between Structure and Class in C++
In C++, a structure works the same way as a class, except for just two small differences. The most important of them is hiding implementation details. A structure will by default not hide its implementation details from whoever uses it in code, while a class by default hides all its implementation d
3 min read
Why C++ is partially Object Oriented Language?
The basic thing which are the essential feature of an object oriented programming are Inheritance, Polymorphism and Encapsulation. Any programming language that supports these feature completely are complete Object-oriented programming language whereas any language that supports all three feature bu
3 min read
C++ Encapsulation and Abstraction
C++ Function Overloading
Function Overloading in C++
Function overloading is a feature of object-oriented programming where two or more functions can have the same name but different parameters. When a function name is overloaded with different jobs it is called Function Overloading. In Function Overloading “Function” name should be the same and the a
4 min read
Constructor Overloading in C++
Prerequisites: Constructors in C++ In C++, We can have more than one constructor in a class with same name, as long as each has a different list of arguments.This concept is known as Constructor Overloading and is quite similar to function overloading. Overloaded constructors essentially have the sa
2 min read
Functions that cannot be overloaded in C++
In C++, following function declarations cannot be overloaded. 1) Function declarations that differ only in the return type. For example, the following program fails in compilation. C/C++ Code #include<iostream> int foo() { return 10; } char foo() { return 'a'; } int main() { char x = f
3 min read
Function overloading and const keyword
Function overloading is a feature of object-oriented programming where two or more functions can have the same name but different parameters. When a function name is overloaded with different jobs it is called Function Overloading. In Function Overloading “Function” name should be the same and the a
5 min read
Function Overloading and Return Type in C++
Function overloading is possible in C++ and Java but only if the functions must differ from each other by the types and the number of arguments in the argument list. However, functions can not be overloaded if they differ only in the return type. Why is Function overloading not possible with differe
2 min read
Function Overloading and float in C++
Although polymorphism is a widely useful phenomena in C++ yet it can be quite complicated at times. For instance consider the following code snippet: C/C++ Code #include<iostream> using namespace std; void test(float s,float t) { cout << "Function with float call
2 min read
Can main() be overloaded in C++?
Predict the output of following C++ program. #include <iostream> using namespace std; int main(int a) { cout << a << "\n"; return 0; } int main(char *a) { cout << a << endl; return 0; } int main(int a, int b) { cout << a << " " << b
2 min read
Function Overloading vs Function Overriding in C++
Function Overloading (achieved at compile time) Function Overloading provides multiple definitions of the function by changing signature i.e. changing number of parameters, change datatype of parameters, return type doesn’t play any role. It can be done in base as well as derived class.Example: void
3 min read
Advantages and Disadvantages of Function Overloading in C++
Function overloading is one of the important features of object-oriented programming. It allows users to have more than one function having the same name but different properties. Overloaded functions enable users to supply different semantics for a function, depending on the signature of functions.
3 min read
C++ Inheritance
Inheritance in C++
The capability of a class to derive properties and characteristics from another class is called Inheritance. Inheritance is one of the most important features of Object Oriented Programming in C++. In this article, we will learn about inheritance in C++, its modes and types along with the informatio
15+ min read
C++ Inheritance Access
Prerequisites: Class-Object in C++Inheritance in C++Before learning about Inheritance Access we need to know about access specifiers. There are three Access specifiers in C++. These are: public - members are accessible from outside the class, and members can be accessed from anywhere.private - membe
4 min read
Multiple Inheritance in C++
Multiple Inheritance is a feature of C++ where a class can inherit from more than one classes. The constructors of inherited classes are called in the same order in which they are inherited. For example, in the following program, B's constructor is called before A's constructor. A class can be deriv
5 min read
C++ Hierarchical Inheritance
Inheritance is a feature of Object-Oriented-programming in which a derived class (child class) inherits the property (data member and member functions) of the Base class (parent class). For example, a child inherits the traits of their parents. In Hierarchical inheritance, more than one sub-class in
4 min read
C++ Multilevel Inheritance
Multilevel Inheritance in C++ is the process of deriving a class from another derived class. When one class inherits another class it is further inherited by another class. It is known as multi-level inheritance. For example, if we take Grandfather as a base class then Father is the derived class th
2 min read
Constructor in Multiple Inheritance in C++
Constructor is a class member function with the same name as the class. The main job of the constructor is to allocate memory for class objects. Constructor is automatically called when the object is created. Multiple Inheritance: Multiple Inheritance is a feature of C++ where a class can derive fro
2 min read
Inheritance and Friendship in C++
Inheritance in C++: This is an OOPS concept. It allows creating classes that are derived from other classes so that they automatically include some of the functionality of its base class and some functionality of its own. (See this article for reference) Friendship in C++: Usually, private and prote
2 min read
Does overloading work with Inheritance?
If we have a function in base class and another function with the same name in derived class, can the base class function be called from derived class object? This is an interesting question and as an experiment, predict the output of the following C++ program: [GFGTABS] C++ #include <iostream
5 min read
Difference between Inheritance and Polymorphism
Inheritance is one in which a new class is created that inherits the properties of the already exist class. It supports the concept of code reusability and reduces the length of the code in object-oriented programming. Types of Inheritance are:Single inheritanceMulti-level inheritanceMultiple inheri
5 min read
C++ Virtual Functions
Virtual Function in C++
A virtual function (also known as virtual methods) is a member function that is declared within a base class and is re-defined (overridden) by a 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 a
6 min read
Virtual Functions in Derived Classes in C++
A virtual function is a member function of a base class that is overridden by a derived class. When you use a pointer or a reference to the base class to refer to a derived class object, you can call a virtual function for that object and have it run the derived class's version of the function. In C
2 min read
Default Arguments and Virtual Function in C++
Default Arguments are the values provided during function declaration, such that values can be automatically assigned if no argument is passed to them. In case any value is passed the default value is overridden and it becomes a parameterized argument. Virtual function is a member function that is d
3 min read
Can Virtual Functions be Inlined in C++?
Virtual functions are member functions that are declared in the base class using the keyword virtual and can be overridden by the derived class. They are used to achieve Runtime polymorphism or say late binding or dynamic binding. Inline functions are used to replace the function calling location wi
2 min read
Virtual Destructor
Deleting a derived class object using a pointer of base class type that has a non-virtual destructor results in undefined behavior. To correct this situation, the base class should be defined with a virtual destructor. For example, the following program results in undefined behavior. C/C++ Code // C
2 min read
Advanced C++ | Virtual Constructor
In C++, we CANNOT make a constructor virtual. The reason is that C++ is a statically typed language, so the concept of a virtual constructor is a contradiction because the compiler needs to know the exact type at compile time to allocate the correct amount of memory and initialize the object correct
8 min read
Advanced C++ | Virtual Copy Constructor
In the virtual constructor idiom we have seen the way to construct an object whose type is not determined until runtime. Is it possible to create an object without knowing it's exact class type? The virtual copy constructor address this question.Sometimes we may need to construct an object from anot
5 min read
Pure Virtual Functions and Abstract Classes in C++
Sometimes implementation of all functions cannot be provided in a base class because we don't know the implementation. Such a class is called an abstract class.For example, let Shape be a base class. We cannot provide the implementation of function draw() in Shape, but we know every derived class mu
6 min read
Pure Virtual Destructor in C++
A pure virtual destructor can be declared in C++. After a destructor has been created as a pure virtual object(instance of a class), where the destructor body is provided. This is due to the fact that destructors will not be overridden in derived classes, but will instead be called in reverse order.
4 min read
Can Static Functions Be Virtual in C++?
In C++, a static member function of a class cannot be virtual. Virtual functions are invoked when you have a pointer or reference to an instance of a class. Static functions aren't tied to the instance of a class but they are tied to the class. C++ doesn't have pointers-to-class, so there is no scen
1 min read
RTTI (Run-Time Type Information) in C++
In C++, RTTI (Run-time type information) is a mechanism that exposes information about an object's data type at runtime and is available only for the classes which have at least one virtual function. It allows the type of an object to be determined during program execution. Runtime Casts The runtime
3 min read
Can Virtual Functions be Private in C++?
A virtual function can be private as C++ has access control, but not visibility control. As mentioned virtual functions can be overridden by the derived class but under all circumstances will only be called within the base class. Example 1: Calling Private Virtual Function from Base Class Pointer to
4 min read
C++ Standard Template Library (STL)
C++ Standard Template Library (STL)
The C++ Standard Template Library (STL) is a set of template classes and functions that provides the implementation of common data structures and algorithms such as lists, stacks, arrays, sorting, searching, etc. It also provides the iterators and functors which makes it easier to work with algorith
9 min read
Containers in C++ STL (Standard Template Library)
A container is a holder object that stores a collection of other objects (its elements). They are implemented as class templates, which allows great flexibility in the types supported as elements. The container manages the storage space for its elements and provides member functions to access them,
2 min read
Introduction to Iterators in C++
An iterator is an object (like a pointer) that points to an element inside the container. We can use iterators to move through the contents of the container. They can be visualized as something similar to a pointer pointing to some location and we can access the content at that particular location u
6 min read
Algorithm Library | C++ Magicians STL Algorithm
For all those who aspire to excel in competitive programming, only having a knowledge about containers of STL is of less use till one is not aware what all STL has to offer. STL has an ocean of algorithms, for all < algorithm > library functions : Refer here.Some of the most used algorithms on
7 min read
Functors in C++
Please note that the title is Functors (Not Functions)!! Consider a function that takes only one argument. However, while calling this function we have a lot more information that we would like to pass to this function, but we cannot as it accepts only one parameter. What can be done? One obvious an
3 min read
C++ Namespace
Namespace in C++ | Set 1 (Introduction)
Namespace provide the space where we can define or declare identifier i.e. variable, method, classes.Using namespace, you can define the space or context in which identifiers are defined i.e. variable, method, classes. In essence, a namespace defines a scope.Advantage of Namespace to avoid name coll
11 min read
namespace in C++ | Set 2 (Extending namespace and Unnamed namespace)
We have introduced namespaces in below set 1.Namespace in C++ | Set 1 (Introduction) Defining a Namespace: A namespace definition begins with the keyword namespace followed by the namespace name as follows: namespace namespace_name {// code declarations i.e. variable (int a;)method (void add();)clas
4 min read
Namespace in C++ | Set 3 (Accessing, creating header, nesting and aliasing)
Namespace in C++ | Set 1 (Introduction) Namespace in C++ | Set 2 (Extending namespace and Unnamed namespace) Different ways to access namespace: In C++, there are two ways of accessing namespace variables and functions. Defining a Namespace: A namespace definition begins with the keyword namespace f
5 min read
C++ Inline Namespaces and Usage of the "using" Directive Inside Namespaces
Prerequisite: Namespaces in C++ In C++, namespaces can be nested, and the resolution of namespace variables is hierarchical. An inline namespace is a namespace that uses the optional keyword inline in its original-namespace definition. This allows the identifiers of the nested inline namespace to be
3 min read
Advanced C++
Multithreading in C++
Multithreading is a feature that allows concurrent execution of two or more parts of a program for maximum utilization of the CPU. Each part of such a program is called a thread. So, threads are lightweight processes within a process. Multithreading support was introduced in C++11. Prior to C++11, w
6 min read
Smart Pointers in C++
Prerequisite: Pointers in C++ Pointers are used for accessing the resources which are external to the program - like heap memory. So, for accessing the heap memory (if anything is created inside heap memory), pointers are used. When accessing any external resource we just use a copy of the resource.
9 min read
auto_ptr vs unique_ptr vs shared_ptr vs weak_ptr in C++
Prerequisite – Smart Pointers Smart Pointer is a pointer-wrapping stack-allocated object. Smart pointers, in plain terms, are classes that wrap a pointer, or scoped pointers. C++ libraries provide implementations of smart pointers in the following types: auto_ptrunique_ptrshared_ptrweak_ptr They all
7 min read
Type of 'this' Pointer in C++
In C++, this pointer refers to the current object of the class and passes it as a parameter to another method. 'this pointer' is passed as a hidden argument to all non-static member function calls. Type of 'this' pointer The type of this depends upon function declaration. The type of this pointer is
2 min read
"delete this" in C++
Ideally delete operator should not be used for this pointer. However, if used, then following points must be considered.1) delete operator works only for objects allocated using operator new (See this post). If the object is created using new, then we can do delete this, otherwise behavior is undefi
1 min read
Passing a Function as a Parameter in C++
Passing a function as an argument is a useful concept in C++. This concept has already been used while passing a custom comparator function as an argument in sort() function to sort a sequence of objects as per the need. In this article, we will discuss different ways to design functions that accept
4 min read
Signal Handling in C++
Signals are the interrupts that force an OS to stop its ongoing task and attend the task for which the interrupt has been sent. These interrupts can pause service in any program of an OS. Similarly, C++ also offers various signals which it can catch and process in a program. Here is a list of variou
3 min read
Generics in C++
Generics is the idea to allow type (Integer, String, … etc and user-defined types) to be a parameter to methods, classes and interfaces. For example, classes like an array, map, etc, which can be used using generics very efficiently. We can use them for any type. The method of Generic Programming is
3 min read
C vs C++
Difference between C and C++
C++ is often viewed as a superset of C. C++ is also known as a "C with class" This was very nearly true when C++ was originally created, but the two languages have evolved over time with C picking up a number of features that either weren't found in the contemporary version of C++ or still haven't m
4 min read
Difference between C++ and Objective C
1. C++ :C++ or CPP is a general-purpose statically typed object-oriented programming language. In 1979, a Danish computer scientist named Bjarne Stroustrup wanted to make an extension to C that would allow it to use classes. This seed has expanded since then and had become one of the most used and w
3 min read
Write a C program that won't compile in C++
Although C++ is designed to have backward compatibility with C, there can be many C programs that would produce compiler errors when compiled with a C++ compiler. Following is the list of the C programs that won’t compile in C++: Calling a function before the declarationUsing normal pointer with con
4 min read
Write a program that produces different results in C and C++
Write a program that compiles and runs both in C and C++, but produces different results when compiled by C and C++ compilers. There can be many such programs, following are some of them. 1) Character literals are treated differently in C and C++. In C character literals like 'a', 'b', ..etc are tre
2 min read
How does 'void*' differ in C and C++?
C allows a void* pointer to be assigned to any pointer type without a cast, whereas in C++, it does not. We have to explicitly typecast the void* pointer in C++ For example, the following is valid in C but not C++: void* ptr; int *i = ptr; // Implicit conversion from void* to int* Similarly, int *j
1 min read
Type Difference of Character Literals in C and C++
Every literal (constant) in C/C++ will have a type of information associated with it. In both C and C++, numeric literals (e.g. 10) will have int as their type. It means sizeof(10) and sizeof(int) will return the same value.If we compile what we have said in terms of code then it will look something
2 min read
Difference Between C Structures and C++ Structures
Let's discuss, what are the differences between structures in C and structures in C++? In C++, structures are similar to classes. Differences Between the C and C++ StructuresC Structures C++ Structures Only data members are allowed, it cannot have member functions.Can hold both: member functions and
6 min read
Cin-Cout vs Scanf-Printf
Regular competitive programmers face common challenge when input is large and the task of reading such an input from stdin might prove to be a bottleneck. Such problem is accompanied with “Warning: large I/O data”. Let us create a dummy input file containing a line with 16 bytes followed by a newlin
3 min read
C++ vs Java
Similarities and Difference between Java and C++
Nowadays Java and C++ programming languages are vastly used in competitive coding. Due to some awesome features, these two programming languages are widely used in industries as well as comepetitive programming . C++ is a widely popular language among coders for its efficiency, high speed, and dynam
6 min read
Comparison of Inheritance in C++ and Java
The purpose of inheritance is the same in C++ and Java. Inheritance is used in both languages for reusing code and/or creating an ‘is-a’ relationship. The following examples will demonstrate the differences between Java and C++ that provide support for inheritance. 1) In Java, all classes inherit fr
4 min read
Static Keyword in C++
The static keyword in C++ has different meanings when used with different types. In this article, we will learn about the static keyword in C++ along with its various uses. In C++, a static keyword can be used in the following context: Table of Content Static Variables in a FunctionStatic Member Var
6 min read
How Does Default Virtual Behavior Differ in C++ and Java?
Let us discuss how the default virtual behavior of methods is opposite in C++ and Java. It is very important to remember that in the C++ language class member methods are non-virtual by default. They can be made virtual by using virtual keywords. For example, Base::show() is non-virtual in following
3 min read
Comparison of Exception Handling in C++ and Java
Both languages use to try, catch and throw keywords for exception handling, and their meaning is also the same in both languages. Following are the differences between Java and C++ exception handling: Java C++ Only throwable objects can be thrown as exceptions.All types can be thrown as exceptions.W
4 min read
Foreach in C++ and Java
Foreach loop is used to iterate over the elements of a container (array, vectors, etc) quickly without performing initialization, testing, and increment/decrement. The working of foreach loops is to do something for every element rather than doing something n times. There is no foreach loop in C, bu
6 min read
Templates in C++ vs Generics in Java
While building large-scale projects, we need the code to be compatible with any kind of data which is provided to it. That is the place where your written code stands above that of others. Here what we meant is to make the code you write be generic to any kind of data provided to the program regardl
4 min read
Floating Point Operations & Associativity in C, C++ and Java
Do Floating point operations follow property of associativity? In other words, do we always get the same results for expressions "(A + B) + C" and "A + (B + C)" One may expect that floating numbers to follow the rule of associativity in programming languages as they are associative mathematically. H
4 min read
Competitive Programming in C++
Competitive Programming - A Complete Guide
Competitive Programming is a mental sport that enables you to code a given problem under provided constraints. The purpose of this article is to guide every individual possessing a desire to excel in this sport. This article provides a detailed syllabus for Competitive Programming designed by indust
8 min read
C++ tricks for competitive programming (for C++ 11)
We have discussed some tricks in the below post. In this post, some more tricks are discussed. Writing C/C++ code efficiently in Competitive programming Although, practice is the only way that ensures increased performance in programming contests but having some tricks up your sleeve ensures an uppe
5 min read
Writing C/C++ code efficiently in Competitive programming
First of all you need to know about Template, Macros and Vectors before moving on the next phase! Templates are the foundation of generic programming, which involve writing code in a way that is independent of any particular type.A Macro is a fragment of code which has been given a name. Whenever th
6 min read
Why C++ is best for Competitive Programming?
C++ is the most preferred language for competitive programming. In this article, some features of C++ are discussed that make it best for competitive programming. STL (Standard Template Library): C++ has a vast library called STL which is a collection of C++ templates to provide common programming d
4 min read
Test Case Generation | Set 1 (Random Numbers, Arrays and Matrices)
The test cases are an extremely important part of any "Software/Project Testing Process". Hence this Set will be very important for all aspiring software developers. The following are the programs to generate test cases. Generating Random Numbers C/C++ Code // A C++ Program to generate test cases fo
12 min read
Fast I/O for Competitive Programming
In competitive programming, it is important to read input as fast as possible so we save valuable time. You must have seen various problem statements saying: " Warning: Large I/O data, be careful with certain languages (though most should be OK if the algorithm is well designed)" . The key for such
4 min read
Setting up Sublime Text for C++ Competitive Programming Environment
Sublime Text is an IDE popular among competitive programmers due to its smooth and simple user interface, customizable plugins and other exciting features. In this article, we will discuss how to set up Sublime Text for competitive programming in C++. Table of Content OverviewStep 1: Creating a Buil
3 min read
How to setup Competitive Programming in Visual Studio Code for C++
GCC compiler installation We need to install GCC compilers for Windows. Linux has already GCC installed. Steps for installation1.Download and Install the MinGW for GCC compiler using this link. 2.Open Control Panel in your system and then select: System (Control Panel) 3.Click on the Advanced system
5 min read
Which C++ libraries are useful for competitive programming?
C++ is one of the most recommended languages in competitive programming (please refer our previous article for the reason) C++ STL contains lots of containers which are useful for different purposes. In this article, we are going to focus on the most important containers from competitive programming
3 min read
Common mistakes to be avoided in Competitive Programming in C++ | Beginners
Not using of 1LL or 1ll when needed // A program shows problem if we // don't use 1ll or 1LL #include <iostream> using namespace std; int main() { int x = 1000000; int y = 1000000; // This causes overflow even // if z is long long int long long int z = x*y; cout << z; return 0; } Output:
7 min read
C++ Interview Questions
C++ Interview Questions and Answers (2024)
C++ - the must-known and all-time favourite programming language of coders. It is still relevant as it was in the mid-80s. As a general-purpose and object-oriented programming language is extensively employed mostly every time during coding. As a result, some job roles demand individuals be fluent i
15+ min read
Top C++ STL Interview Questions and Answers
The Standard Template Library (STL) is a set of C++ template classes that are used to implement widely popular algorithms and data structures such as vectors, lists, stacks, and queues. It is part of the C++ Language ISO standard. STL is a popular topic among interviewers, so it is useful for both f
15+ min read
30 OOPs Interview Questions and Answers (2024) Updated
Object-oriented programming, or OOPs, is a programming paradigm that implements the concept of objects in the program. It aims to provide an easier solution to real-world problems by implementing real-world entities such as inheritance, abstraction, polymorphism, etc. in programming. OOPs concept is
15+ min read
Top C++ Exception Handling Interview Questions and Answers
Exception Handling is one of the most important topics from the C++ Interview perspective. Exception handling is an effective means to handle the runtime errors that disrupt the normal flow of the program. It is one of the most used concepts in real-world embedded systems so it is common to encounte
8 min read
C++ Programming Examples
Writing C++ programs yourself is the best way to learn the C++ language. C++ programs are also asked in the interviews. This article covers the top practice problems for basic C++ programs on topics like control flow, patterns, and functions to complex ones like pointers, arrays, and strings. C++ Tu
9 min read
C++ Interview Questions and Answers (2024)
C++ - the must-known and all-time favourite programming language of coders. It is still relevant as it was in the mid-80s. As a general-purpose and object-oriented programming language is extensively employed mostly every time during coding. As a result, some job roles demand individuals be fluent i
15+ min read
Top 50 C++ Project Ideas For Beginners & Advanced
C++ is one of the most popular programming languages widely used in the software industry for projects in different domains like games, operating systems, web browsers, DBMS, etc due to its fast speed, versatility, lower-level memory access, and many more. Many top companies like Microsoft, Google,
15+ min read