Below is a compilation of common C++ interview inquiries along with their corresponding responses:
1) What is C++?
C++ is a programming language based on object-oriented principles, enabling developers to operate within an environment of objects and classes, facilitating clearer comprehension and management. Bjarne Stroustrup, a Computer Science professor at Columbia University in New York, conceptualized and developed the C++ language, which became available in 1985.
Essentially, C++ represents a more sophisticated iteration of the C programming language, building upon procedural programming principles. C++ embraces fundamental object-oriented programming (OOP) principles like encapsulation, inheritance, and polymorphism. Consequently, we can affirm that C++ serves as an extension of the C programming language.
2) What are the advantages of C++?
Several advantages of C++ programming languages are as follows:
- C++ not only maintains all aspects of the C programming language, it also simplifies memory management and adds several features to the code.
- C++ is a highly portable language means that the software developed using C++ language can run on any platform.
- C++ is an object-oriented programming language that includes the OOPs concepts, such as classes, objects, inheritance, polymorphism, and abstraction.
- C++ uses a technique called message passing that is used for making communication between the objects.
- C++ contains a rich function library that we can use in our code and brings in the dependency in the user's code.
3) What is the difference between C and C++?
There exist multiple variances between the C and C++ programming languages. A few of these disparities include:
| C | C++ |
|---|---|
| C language was developed by Dennis Ritchie. | C++ language was developed by Bjarne Stroustrup. |
| C is a structured programming language. | C++ supports both structural and object-oriented programming language. |
| C is a subset of C++. | C++ is a superset of C. |
| In C language, data and functions are free entities. | In the C++ language, both data and functions are encapsulated together in the form of a project. |
| C does not support data hiding. Therefore, the data can be used by the outside world. | C++ supports data hiding. Therefore, the data cannot be accessed by the outside world. |
| C supports neither function nor operator overloading. | C++ supports both function and operator overloading. |
| In C, the function cannot be implemented inside the structures. | In C++, the function can be implemented inside the structures. |
| Reference variables are not supported in C language. | C++ supports the reference variables. |
| C language does not support the virtual and friend functions. | C++ supports both virtual and friend functions. |
| In C, scanf() and printf() are mainly used for input/output. | C++ mainly uses stream cin and cout to perform input and output operations. |
To Read More: Difference between C and C++
4) What is the difference between a Reference and a Pointer?
There are various variances between references and pointers in C++. Some key variations include:
| Reference | Pointer |
|---|---|
| Reference behaves like an alias for an existing variable, i.e., it is a temporary variable. | The pointer is a variable that stores the address of a variable. |
| Reference variable does not require any indirection operator to access the value. A reference variable can be used directly to access the value. | Pointer variable requires an indirection operator to access the value of a variable. |
| Once the reference variable is assigned, then it cannot be reassigned with different address values. | The pointer variable is an independent variable means that it can be reassigned to point to different objects. |
| A null value cannot be assigned to the reference variable. | A null value can be assigned to the reference variable. |
| It is necessary to initialize the variable at the time of declaration. | It is not necessary to initialize the variable at the time of declaration. |
To Read More: Difference between Reference and Pointer
5) What is a Class in C++?
In C++, a class represents a custom data type created by the user. It is declared with the keyword "class" and consists of data members and member functions. The access to these members is determined by the modifiers private, public, and protected. Essentially, a class establishes the blueprint for a specific category of objects. While it defines a datatype, it does not actually hold any data; its role is to outline the structure of the data.
If we wish to utilize the information stored within that class, we instantiate multiple objects within the class and call upon the methods and variables.
Syntax
It has the following syntax:
class < class name >
{
< access modifier > ( private, public, protected ) :
// data member
// member method
} ;
C++ Class Example
Let's consider an example to demonstrate the concept of a class in C++.
Example
#include <iostream>
using namespace std;
class Test {
public:
// data members
int sum;
int a = 2;
int b = 3;
// member method
void add(int a, int b) {
sum = a + b;
cout << "The sum of a and b is: " << sum << endl;
}
};
int main() {
Test obj;
obj.add(obj.a, obj.b);
return 0;
}
Output:
The sum of a and b is: 5
To Read More: C++ Classes
6) What are the various OOP concepts in C++?
Several OOP concepts in C++ are as follows:
Class
In C++, a class serves as a custom data type created by the user to specify its attributes and behaviors. To illustrate, consider humans as a class. The body parts of a human constitute its attributes, while the tasks executed by these body parts are identified as functions. Notably, a class does not consume any memory allocation, signifying that it solely serves as the abstract blueprint of the data.
Syntax
It has the following syntax:
class student
{
//data members;
//Member functions
}
Object
In C++, an object is a dynamic entity that serves as an instance of a class. Objects can embody various entities like individuals, locations, or objects. They are capable of interacting with both data attributes and methods within the class. It's important to note that classes themselves do not consume any memory allocation.
When an instance is instantiated using the new operator, memory is reserved for the object on the heap, and the initial memory address is saved in the stack. Conversely, if an object is created without utilizing the new keyword, heap memory is not reserved, resulting in the object storing a null value on the stack.
Syntax
It has the following syntax:
Student s = new Student();
Inheritance
In C++, inheritance offers the benefit of reusability by enabling the utilization of functionalities from an existing class. This approach helps in reducing code redundancy. Inheritance involves creating a new class based on an existing class, where the existing class is referred to as the base class and the new class as the derived class.
Syntax
It has the following syntax:
class derived_class :: visibility-mode base_class;
Note: The visibility mode can be public, private, or protected
To Read More: C++ Inheritance
Encapsulation
In C++, encapsulation serves as a method of enclosing both the data attributes and member procedures within a unified entity. This process securely ties the data within a class, preventing external methods from directly interacting with the data. When a data member is marked as private, only the member functions have the privilege to manipulate the data.
To Read More: C++ Encapsulation
Abstraction
In C++, abstraction is a method that involves displaying only crucial details while concealing the implementation specifics. When members are declared using the public keyword, they are accessible externally. Conversely, when members are declared with the private keyword, they are not accessible to external functions.
To Read More: C++ Abstraction
Polymorphism
Static polymorphism, also referred to as early binding, involves having multiple functions with the same name but differing functionalities in C++. On the other hand, dynamic polymorphism, known as late binding, is the second type of polymorphism in C++.
7) What are the different types of Polymorphism in C++?
In C++, polymorphism refers to the concept of having multiple forms. This entails having multiple functions sharing the same name while offering different functionalities.
Polymorphism primarily exists in two forms:
- Dynamic Polymorphism
Runtime polymorphism, also referred to as dynamic polymorphism, occurs when a function in a child class overrides a method that is already defined in the parent class. This results in the child class substituting the method of the parent class. When function overriding takes place, both the parent and child classes have the same function but with distinct implementations. The decision of which function to call is made during runtime, hence the term "runtime polymorphism."
C++ Runtime Polymorphism Example
Let's consider an example to demonstrate the concept of Runtime Polymorphism in C++.
Example
#include <iostream>
using namespace std; //using standard namespace
class Base
{
public:
virtual void show()
{
cout<<"cpp tutorial";
}
};
class Derived:public Base
{
public:
void show()
{
cout<<"cpp tutorial tutorial";
}
};
int main() //main function
{
Base* b;
Derived d;
b=&d;
b->show();
return 0;
}
Output:
cpp tutorial tutorial
- Compile time Polymorphism
In C++, static polymorphism is another term for compile-time polymorphism. Compile-time polymorphism refers to polymorphism that is enforced during the compilation process. An instance of compile-time polymorphism is method overloading.
To Read More: C++ Polymorphism
8) What is Method Overloading in C++?
In C++, method overloading is a strategy that enables the inclusion of several functions using the same name but with distinct behaviors.
Method overloading can be possible on the following basis:
- The return type of the overloaded function.
- The type of the parameters passed to the function.
- The number of parameters passed to the function.
Method Overloading Example
Example
#include <iostream>
using namespace std; //using standard namespace
class Multiply
{
public:
int mul(int a,int b)
{
return(a*b);
}
int mul(int a,int b,int c)
{
return(a*b*c);
}
};
int main() //main function
{
Multiply multi;
int res1,res2;
res1=multi.mul(2,3);
res2=multi.mul(2,3,4);
cout<<"\n";
cout<<res1;
cout<<"\n";
cout<<res2;
return 0;
}
Output:
Explanation:
In the previous instance, the null function is overloaded with varying parameter quantities.
9) What is the Namespace in C++?
- The namespace is a logical division of the code that is designed to stop the naming conflict.
- The namespace defines the scope where the identifiers, such as variables, classes, and functions, are declared.
- The main purpose of using namespace in C++ is to remove the ambiguity. Ambiguity occurs when a different task occurs with the same name.
- For example, if there are two functions that exist with the same name, such as add. The namespace is used to prevent this ambiguity. Functions are declared in different namespaces.
- C++ consists of a standard namespace, i.e., std which contains inbuilt classes and functions. So, by using the statement "using namespace std;" includes the namespace "std" in our program.
Syntax of Namespace:
namespace namespace_name
{
//body of namespace;
}
Syntax of Accessing the Namespace Variable:
namespace_name::member_name;
C++ Namespace Example
Let's consider an example to demonstrate the concept of namespace in C++.
Example
#include <iostream>
using namespace std; //using standard namespace
namespace addition
{
int a=5;
int b=5;
int add()
{
return(a+b);
}
}
int main() { //main function
int result;
result=addition::add();
cout<<result;
return 0;
}
Output:
To Read More: C++ Namespace
10) What is Token in C++?
Tokens represent the tiniest standalone components within a C++ program, essential for the compiler to conduct lexical analysis and comprehend the code. Through these tokens, we identify, interpret, handle, and structure the syntax of the programming language. A token may take the form of a keyword, identifier, literal, constant, or symbol.
To Read More: Tokens in C++
11) Which operations are permitted on Pointers?
There exist numerous actions that can be executed on pointers in C++. Some primary operations include:
- Increasing or decreasing a pointer: Elevating a pointer involves adding the size of the data type it points to.
There exist two categories of increment operators:
- Pre-Increment Operator: This operator increases the operand by 1 before using its value in the expression. For instance, if ptr is a pointer, the pre-increment operator is denoted as ++ptr.
C++ Pre-Increment Pointer Example
Let's consider an example to demonstrate the pre-increment operator in C++.
Example
#include <iostream>
using namespace std; //using standard namespace
int main() //main function
{
int a[5]={1,2,3,4,5};
int *ptr;
ptr=&a[0];
cout<<"Value of *ptr is : "<<*ptr<<"\n";
cout<<"Value of *++ptr : "<<*++ptr;
return 0;
}
Output:
The post-increment operator increases the operand by 1, however, the result of the expression will be the original value of the operand before the increment. When dealing with a pointer like ptr, the post-increment operator is denoted as ptr++.
C++ Post-Increment Example
Let's consider an example to demonstrate the post-increment operator in the C++ programming language.
Example
#include <iostream>
using namespace std; //using standard namespace
int main() //main function
{
int a[5]={1,2,3,4,5};
int *ptr;
ptr=&a[0];
cout<<"Value of *ptr is : "<<*ptr<<"\n";
cout<<"Value of *ptr++ : "<<*ptr++;
return 0;
}
Output:
Subtracting one pointer from another pointer in C programming involves determining the number of elements between the two memory locations they point to within an array.
12) What is the 'std' in C++?
The std namespace is the primary namespace standard utilized in C++. It encompasses all the declarations (classes, functions, objects, etc.) specified in the C++ Standard Library.
When utilizing functionalities such as cout, cin, string, vector, sort, and more, they are all components within the std namespace. This practice aids in preventing naming clashes and maintaining a well-structured collection of standard library identifiers.
13) Which programming language's unsatisfactory performance led to the discovery of C++?
C++ was developed to address the limitations of C.
14) How delete is different from delete?
In C++, the delete keyword is employed to free a single block of memory, while the delete operator is utilized to release memory allocated for an array.
15) What is the full form of STL in C++?
In C++, the STL acronym represents the Standard Template Library.
To Read More: C++ STL
16) What is an Object in C++?
In C++, an object represents an instance of a class that enables us to access the attributes and actions defined within the class multiple times by creating multiple objects. The core principle of object-oriented programming revolves around objects as they facilitate code reusability for developers.
Objects within a class are instantiated in a similar manner to declaring variables of primitive types. Instances are constructed within a class by specifying the class name followed by the object name. It is also possible to instantiate objects dynamically by utilizing the "new" keyword, resulting in memory allocation in the heap memory area. Object access is achieved through the dot operator.
C++ Object Example
Let's consider an example to demonstrate the concept of Object in C++.
Example
#include <iostream>
using namespace std; //using standard namespace
class Test {
public:
string str = " Hello ";
void display ( ) {
cout << str << endl;
}
};
int main( ) {
// create the object
Test obj;
// Invoking the method using the dot operator.
obj.display ( );
return 0;
}
Output:
17) What are the C++ Access Specifiers?
In C++, access specifiers play a crucial role in determining the accessibility of functions and variables outside the class. They are essential for specifying the extent to which methods and variables can be accessed from external sources.
We have the following three types of access specifiers:
- Private Access Specifier: If we use the private specifier over a method or variable, it can be accessed only within the same class and cannot be accessed outside the class. They become private to the class where they have been created and initialized.
- Public Access Specifier: If we use the public specifier over a method or variable, it can be accessed from anywhere.
- Protected Access Specifier: Functions and variables declared as protected that cannot be accessed outside the class except a child class. It is generally used in the concept of inheritance, where if we create a parent class and a child class, the methods and variables of the parent class can be accessed by its child class if we have used the protected specifier in the parent class.
To Read More: C++ Access Specifiers
18) What is Object Oriented Programming (OOP)?
In C++, OOP represents a methodology or paradigm enabling developers to interact with tangible entities in a comprehensible manner. The idea behind object-oriented programming involves the creation of objects to carry out specified functions. Several fundamental principles collectively form the foundation of OOP.
Classes and Objects: Classes define the blueprint of the data structure. Within a class, we define and set up methods and variables that establish the framework of the data. Additionally, we have the ability to designate the access levels of a class as public, private, or protected.
On the contrary, objects represent the specific occurrences of classes that we utilize to invoke the specified methods and variables within the class. By creating multiple objects, we can repeatedly access the methods and variables of a class across various situations.
Encapsulation refers to a technique that combines data and its related functions, effectively shielding the data from external access. This concept is commonly referred to as data hiding. In C++, this encapsulation is accomplished through access specifiers such as public, private, and protected.
When a class is constructed, data attributes and methods are enclosed within it, consolidating them into a cohesive unit. This process of encapsulation involves organizing them within a class, serving as a simple illustration to grasp the concept. By encapsulating data within a class, only essential elements are exposed to users, while the rest of the data is kept private.
Abstraction involves concealing the inner workings and revealing only essential information to external entities. Various methods can be employed to achieve abstraction. In C++, data abstraction is accomplished through the utilization of interfaces and abstract classes.
Inheritance enables the transfer of attributes from one class to another, establishing a relationship where one class is defined in relation to another. Through inheritance, a hierarchical structure is formed, creating an IS-A connection between classes and fostering code reusability by sharing methods and variables across multiple classes.
In the concept of inheritance, there exists a base class (referred to as the Parent class) along with one or multiple child classes. Should the need arise to utilize a method from the parent class within a child class, it is possible to instantiate objects and call upon the method, and the reverse is also true.
To Read More: OOPs Concept in C++
19) What are the differences between an Array and a List?
There are several differences between an array and a list. Some main differences between them are as follows:
- An Array is a collection of homogeneous elements, while a list is a collection of heterogeneous elements.
- Array memory allocation is static and continuous, while List memory allocation is dynamic and random.
- In Array, users don't need to keep track of the next memory allocation, while In the list, the user has to keep track of the next location where memory is allocated.
20) What are the differences between new and malloc?
There are several differences between a new and a malloc. Some main differences between them are as follows:
- The new operator is a preprocessor , malloc is a function.
- There is no need to allocate the memory while using "new", but in malloc, we have to use the sizeof function.
- The "new" initializes the new memory to 0, while malloc gives a random value in the newly allotted memory location.
- The new operator allocates the memory and calls the constructor for the object initialization, and the malloc function allocates the memory but does not call the constructor for the object initialization.
- The new operator is faster than the malloc function because the operator is faster than the function.
To Learn More: Variances between the new Method and malloc Function
21) What are the methods of exporting a function from a DLL?
There are two methods:
- Utilizing the type library of the DLL.
- Obtaining a reference to the function directly from the DLL instance.
22) Define Friend Function in C++.
In C++, the friend function serves as a companion to the class. It has the capability to reach the private and protected elements within the class. Although not considered a class member, the friend function needs to be declared within the class definition.
Non-member functions are unable to reach the private data within a class. Occasionally, it becomes essential for non-member functions to retrieve this data. In such cases, a friend function, being a non-member function, is granted the capability to access the private data of the class.
To ensure compatibility between an external function and the class, it is necessary to designate the function as a friend of the class, as illustrated:
class sample
{
// data members;
public:
friend void abc(void);
};
C++ Friend Function Example
Let's consider an example to demonstrate the friend function in C++.
Example
#include <iostream>
using namespace std; //using standard namespace
class Addition
{
int a=5;
int b=6;
public:
friend int add(Addition a1)
{
return(a1.a+a1.b);
}
};
int main() //main function
{
int result;
Addition a1;
result=add(a1);
cout<<result;
return 0;
}
Output:
To read More: Friend Function in C++
23) What is a Virtual Function?
- In C++, a virtual function is used to replace the implementation provided by the base class. The replacement is always called whenever the object in question is actually of the derived class, even if the object is accessed by a base pointer rather than a derived pointer.
- It is a member function that is present in the base class and redefined by the derived class.
- When we use the same function name in both the base and derived classes, the function in the base class is declared with a keyword virtual.
- When the function is made virtual, C++ determines at run-time which function is to be called based on the type of the objeccpp tutorialed by the base class pointer. Therefore, we can execute different versions of the virtual functions by making the base class pointer to point to different objects.
Rules of a virtual function:
- The virtual functions should be a member of some class.
- The virtual function cannot be a static member.
- Virtual functions are called by using the objeccpp tutorialer.
- It can be a friend of another class.
- C++ does not contain virtual constructors but can have a virtual destructor.
To Read More: C++ Virtual Function
24) When should we use Multiple Inheritance?
In C++, employing multiple Inheritance becomes necessary when a class needs to acquire attributes (both data members and member functions) from multiple base classes. Each base class provides distinct functionality or behavior that is essential for the derived class.
To Read More: Multiple Inheritance in C++
25) What is a Destructor in C++?
In C++, a destructor is a member function responsible for releasing any additional resources allocated by the object. The destructor is invoked automatically when the object is no longer in scope, ensuring proper cleanup of class objects.
Rules of destructor:
- Destructors have the same name as the class name, and it is preceded by a tilde.
- It does not contain any argument and no return type.
- We cannot have more than one destructor defined.
- We cannot overload a destructor.
- A destructor cannot be declared as static or const.
Syntax of a Destructor:
~ < class name > ( ) {
// destructor message
}
Example of a Destructor
Example
#include <iostream>
using namespace std; //using standard namespace
class Test {
public:
// Creating constructor
Test() {
cout << "Constructor Created" <<endl ;
}
// Creatibg destructor
~Test( ) {
cout << "Destructor Created";
}
};
int main() //main function
{
Test obj;
return 0;
}
Output:
Constructor Created
Destructor Created
To Read More: C++ Destructor
26) What is an Overflow Error?
In C++, an overflow error is a form of arithmetic error that happens when the outcome of a mathematical operation surpasses the storage limit of the data type or memory area. This issue can manifest with integers, floating-point data types, or the program's stack.
In C++, each data type comes with a specific range. Overflow happens when a computation results in a value exceeding the maximum boundary within that range.
27) What is Overloading in C++?
- The concept of overloading is when a function has the same name with different arguments, i.e., the single object behaves in different ways and provides different versions of the same function.
- C++ facilitates the programmer to specify more than one definition for a function name or an operator in the same scope.
- When we overload a method, it is called Method Overloading, and when we overload an operator, it is called Operator Overloading.
So, essentially, C++ offers two forms of overloading, namely function overloading and operator overloading.
- Operator Overloading: This involves compile-time polymorphism where a built-in operator is redefined to have a custom implementation. For instance, the '+' operator can be redefined to handle addition operations on various data types like int, float, etc.
Syntax of Operator Overloading:
return_type classname :: Operator Operator_symbol(argument_list)
{
// body_statements;
}
To Learn More: Operator Overloading in C++
- Method Overloading: Within C++, method overloading represents another form of compile-time polymorphism, allowing the creation of a group of methods sharing the same name. These methods execute varying actions according to the arguments provided during the method call. The specific method executed is determined by both the quantity and data type of the arguments within the argument list.
To Read More: Function Overloading in C++
28) What is Function Overriding?
If a derived class inherits a base class and redefines one of the base class's functions within the derived class, it creates an overridden function, which is a key concept in function overriding. This process is crucial for achieving polymorphism. There are two primary types of function overriding:
- Compile Time Overriding: This form of overriding occurs during the compilation phase. Compile-time polymorphism is also referred to as Early Binding or static binding.
- Runtime Function Overriding: In this type of overriding, the method is overridden at runtime. Runtime polymorphism is also known as Dynamic Binding or Late binding. Virtual functions play a pivotal role in achieving runtime polymorphism.
To Read More: C++ Function Overriding
29) What is Virtual Inheritance?
In C++, utilizing virtual inheritance allows developers to generate a single instance of each object, regardless of how many times the object is present within the hierarchy.
30) What is a Constructor?
In C++, a constructor is a unique function responsible for initializing an instance. It must share the identical name with the class. These special functions are invoked automatically each time an instance of a class is instantiated.
Syntax of C++ Constructor
< class name > ( ) {
// initialize the variables or print the message.
}
Basically, there are four types of C++ constructors which are :
- Default Constructor: It is an automatic constructor that is generated by the compiler if we do not create one. Otherwise, it is not generated if we explicitly create our own constructor. With this, it does not carry any parameter and only initializes the objects with their default values.
- Parameterized Constructor: In this constructor, we pass the parameters to the constructor and using these parameters we initialize the objects of the class. However, if we create a parameterized constructor, a non-parameterized constructor should also be defined because when we make our own constructor, the compiler will not create the default constructor.
- Copy Constructor: The constructor that takes a reference to an object of the same class and initializes an object of a class by taking the help of another object of the same class.
- Move Constructor: It is similar to the copy constructor, which creates an object from the existing object. It does not copy the object in the new memory and uses move semantics for transferring the ownership of the created object to the new one without the need to make any extra copies. The process of the move constructor is similar to stealing the resources from the other objects.
To Read More: C++ Constructor
31) What is the purpose of the "delete" operator?
The "delete" keyword is employed to deallocate the dynamically allocated memory by the "new" operator. The delete operator has a return type of void and does not yield any value upon execution. Upon using the delete operator, the object pointer remains intact; only the memory allocated to the object is released.
32) Explain "this" pointer.
In C++, the "this" pointer serves as a keyword that stores the memory address of the current object, which belongs to the class in which it is defined.
To Read More: C++ this Pointer
33) What does the Scope Resolution operator do?
The double colons (::) symbolizes the scope resolution operator, serving the purpose of retrieving data members and member functions from a different class within the current class. To illustrate, suppose class A contains variables v1 and v2. To access these variables in class B, we can employ the scope resolution operator to reach v1 and v2 within class B too.
Syntax of scope resolution operator
Classname:: < variable name or method name >.
If there is a need to retrieve global variables or static variables, declaring a function outside the class or accessing a variable from a parent class within a child class is essential. In such scenarios, scope resolution plays a crucial role in addressing these requirements.
To Read More: Scope Resolution Operator in C++
34) What is a Pure Virtual Function?
In C++, a pure virtual function is a virtual function lacking a concrete implementation. The regular function is marked with the virtual keyword, while the pure virtual function concludes with 0.
Syntax of a pure virtual function
virtual void abc()=0; //pure virtual function.
C++ Pure Virtual Function Example
Let's consider an example to demonstrate the concept of Pure Virtual Function in the C++ programming language.
Example
#include<iostream>
using namespace std; //using standard namespace
class Base
{
public:
virtual void show()=0;
};
class Derived:public Base
{
public:
void show()
{
cout<<"cpp tutorial";
}
};
int main() //main function
{
Base* b;
Derived d;
b=&d;
b->show();
return 0;
}
Output:
cpp tutorial
35) What is the difference between struct and class?
| Structures | class |
|---|---|
| A structure is a user-defined data type that contains variables of dissimilar data types. | The class is a user-defined data type that contains member variables and member functions. |
| The variables of a structure are stored in the stack memory. | The variables of a class are stored in the heap memory. |
| We cannot initialize the variables directly. | We can initialize the member variables directly. |
| If the access specifier is not specified, then by default, the access specifier of the variable is "public". | If the access specifier is not specified, then by default, the access specifier of a variable is "private". |
| Declaration of a structure:struct structure_name{// body of structure;} ; | Declaration of class:class class_name{// body of class;} |
| A structure is declared by using a struct keyword. | The class is declared by using a class keyword. |
| The structure does not support the inheritance. | The class supports the concept of inheritance. |
| The type of a structure is a value type. | The type of a class is a reference type. |
To Read More: Difference between Structure and Class in C++
36) What is a class template?
In C++, a class template is employed to generate a set of classes and functions. For instance, we can develop a template for an array class, allowing us to instantiate arrays of different types like int, float, char, and more. Likewise, we can establish a template for a function; let's say we define a function add; and subsequently, we can instantiate numerous variations of add.
Syntax of a class template:
template<class T>
class classname
{
// body of class;
};
Syntax of an object of a template class:
classname<type> objectname(arglist);
37) What is the difference between function overloading and operator overloading?
Several distinctions between function overloading and operator overloading in C++ are as outlined below:
- Function overloading: This concept allows for having multiple variations of a function with different signatures, indicating they possess a distinct set of parameters.
- Operator overloading: Operator overloading involves redefining standard operators to bestow them with a unique functionality when utilized on class instances.
38) What is a Virtual Destructor?
In C++, a virtual destructor is employed in the base class to ensure proper destruction of objects in derived classes. To declare a virtual destructor, the ~ tilde operator is used followed by the virtual keyword preceding the destructor.
Note: The constructor cannot be virtual, but the destructor can be virtual.
C++ Virtual Destructor Example
Let's consider a scenario to demonstrate the concept of a virtual destructor in the C++ programming language.
Example
#include <iostream>
using namespace std;
class Base
{
public:
Base()
{
cout<<"Base constructor is called"<<"\n";
}
virtual ~Base()
{
cout<<"Base class object is destroyed"<<"\n";
}
};
class Derived:public Base
{
public:
Derived()
{
cout<<"Derived class constructor is called"<<"\n";
}
~Derived()
{
cout<<"Derived class object is destroyed"<<"\n";
}
};
int main()
{
Base* b= new Derived;
delete b;
return 0;
}
Output:
Base constructor is called
Derived class constructor is called
Derived class object is destroyed
Base class object is destroyed
When employing the virtual destructor, the destructor of the derived class is invoked initially, followed by the invocation of the base class destructor.
To Read More: Virtual Destructor in C++
39) What is the difference between Java and C++?
Both Java and C++ are popular programming languages that have their unique features. Several differences between Java and C++ are as follows:
- C++ is basically used for system programming, whereas Java is used for application programming.
- C++ is an extension of the C programming language, whereas Java was designed and created as an interpreter for printing systems.
- The C++ programming language supports the goto statements, whereas Java does not support goto statements.
- C++ supports pointers, whereas Java internally supports pointers.
- C++ supports operator overloading, and Java supports operator overloading.
- In C++, memory management is done manually using new and delete, whereas in Java, memory management is done automatically by the Java Garbage Collector.
To Read More: Difference between Java and C++
40) Define Inline Function in C++.
In C++, an inline function is a function that is implemented with the inline keyword. When using an inline function, the compiler substitutes the function call with the actual code of the function at compile time. The primary objective is to optimize program performance by minimizing the function call overhead.
Inline functions can enhance code performance by inserting the function code directly at the function call site. Whenever alterations are applied to an inline function, it is essential to recompile the function. This is necessary as the compiler needs to refresh all instances where the function code was integrated. Neglecting to do so may result in the program executing with the previous functionality intact.
Syntax:
It has the following syntax:
inline return_type function_name(parameters)
{
// Function Code
}
To Read More: Inline Functions in C++