C++ Interview Questions
C++ Interview Questions
C++ Interview Questions
What is C++?
As an extension of the C language, C++ was developed by Bjarne Stroustrup as a general purpose cross-platform language
which gives programmers a high level of control over system resources and memory.
If there are two or more functions with the same name defined in different libraries then how will the compiler know which
one to refer to? Thus namespace came to picture. A namespace defines a scope and differentiates functions, classes, variables
etc. with the same name available in different libraries. The namespace starts with the keyword “namespace”. The syntax for
the same is as follows:
1 namespace namespace_name {
2 // code declarations
3 }
There are three ways to input a string, using cin, get, and getline. All three methods are mentioned in the sample program
below.
1
2 #include <iostream>
3 using namespace std;
4
int main()
5 {
6 char s[10];
7
8 cout << "Enter a string: ";
9 cin >> str;
10
cout << "\nEnter another string: ";
11 cin.get(s, 10);
12
13 getline(cin, str);
14
15 return 0;
16 }
17
An overloaded declaration is a declaration in the same scope of function or operator declared with the same name more than
once.
C++ is a programming language which is an extension of C. Thus, one should prefer to learn C first (it’s not necessary). After
learning C, then understand the basic difference between C and C++. Implement all the basic programs you learnt in C in C++
also. Then dive into the OOPs concept of C++. Do as many hands-on as possible to understand basic OOPs, and then dive into
advanced level OOPs. When all the basics are clear, build a small game to understand the structure and remain concepts if
any. By following all these steps one can learn C++.
The difference between c and c++ is that C++ is a object oriented language, which means that it has all the features of C as
well as its own thing that is the concept of OOP. C++ has many functionalities of OOP that are missing from C such as
encapsulation, abstraction, classes, objects, etc.
1
2
#include<iostream>
3 #include<string.h>
4 using namespace std;
5 int main ()
6 {
char n[50], t;
7 int i, j;
8 cout << "Enter a string : ";
9 gets(n);
10 i = strlen(n) - 1;
11 for (j = 0; j < i; j++,i--)
{
12 t = s[j];
13 s[j] = s[i];
14 s[i] = t;
15 }
cout << "\nReverse string : " << s;
16
return 0;
17 }
18
19
A template in C++ is used to pass data types as parameters . These make it easier and more simpler to use classes and
functions.
1
template <typename T>
2
3 int fun (T a,T b)
4 {
5 return (a+b);
6 }
7
int main(){
8 cout<<fun<int>(11,22);
9 }
10
Pointers in C++ are a data type that store the memory address of another variable.
For eg.
A function in C++ is a block of code that can be referenced from anywhere in the system and that serves a specific purpose.
1 int fun(){
int a = 11;
2 return 11;
3 }
4
5
int main(){
6
7
int b = fun();
8 }
9
Destructors in c++ are special function/methods that are used to remove memory allocation for objects. They are called
usually when the scope of an object ends. eg. when a function ends you can call a destructor. They are of the same name as
the class – syntax – ~<classname>();
There are 2 approaches to convert integer variables to string. Both the approaches with a sample code are mentioned below.
1 Approach-1
#include<iostream>
2 #include<string>
3 using namespace std;
4 void main()
5 {
6 int n= 1;
string s= to_string(n);
7 cout << s;
8 }
9
10 Approach-2
11
12 #include<iostream>
13 #include <sstream>
#include <string>
14 using namespace std;
15 int main()
16 {
17 int n = 17;
18
// declaring output string stream
19
ostringstream s1;
20
21 // Sending a number as a stream into output str
22 s<< n;
23 // the str() converts number into string
24 string fin = s.str();
// Displaying the string
25 cout << fin;
26 return 0;
27 }
28
29
30
31
32
Function Overloading happens in C++ when two or more functions share the same name. They can be differentiated on the
basis of the type of data they are passing as parameters or even the number of paramters they are passing. eg. int fun(char a);
& int fun(int b); & void fun(int a, int b)
Stl is the standard template library. It is a library that allows you to use a standard set of templates for things such as:
Algorithms, functions, Iterators in place of actual code.
1 queue<int> Q;
2
3 for(k=0;k<10;k++)
4 {
5 Q.push(k);
}
6
Type casting in C is used to change the data type. They are of two types: Implicit Type Conversion: It is automatic. Explicit
Type Conversion: It is user-defined.
A string is a sequence of characters. In C++, string is a data type as well as a header file. This header file consists of powerful
functions of string manipulation. A variable of string is declared as follows:
1
2 #include <iostream>
#include <string>
3 using namespace std;
4
5 int main()
6 {
7 string s;
8
9 cout << "Enter the sentence";
getline(cin, s);
10 cout << str;
11 return 0;
12 }
13
Stream refers to a stream of characters to be transferred between program thread and i/o.
There are 95 reserved keywords in C++ which are not available for re-definition or overloading.
It is a header file that includes basic objects such as cin, cout, cerr, clog.
In C++ programming, the space can be given using the following code.
cout << ” ” ;
There are several methods by which one can allocate memory to 2D array dynamically one of which is as follows.
1
2 #include <iostream>
3 int main()
4 {
int row = 2, col = 2;
5 int* a = new int[row * col];
6
7 int i, j, count = 0;
8 for (i = 0; i < row; i++)
9 for (j = 0; j < col; j++)
10 *(a+ i*col + j) = count++;
11
for (i = 0; i < row; i++)
12 for (j = 0; j < col; j++)
13 printf("%d ", *(a + i*col + j));
14
15 delete[ ] a;
16 return 0;
17 }
18
Goto statement provided unconditional jump in the code. The syntax is: goto label;
1 label: statement;
2
#include <iostream>
3
4
5 using namespace std;
6
7 void main () {
8 float d, avg, add = 0.0;
9 int j, n;
10 cin >> n;
11
for(j = 1; j <= n; ++j)
12 {
13 cout << "Enter number" << i;
14 cin >> d;
15
16 if(d < 0.0)
17 {
goto jump;
18 }
19 add+= d;
20 }
21
22 jump:
23 avg = add/ (j- 1);
cout << avg;
24 }
25
26
When a function with same name is present in both parent and child class then it is called function overriding.
1
2
#include <iostream>
3 using namespace std;
4 class parent {
5 public:
6 void display(){
cout<<"Parent Class";
7 }
8 };
9 class child: public parent{
10 public:
11 void display() {
cout<<"Child Class";
12 }
13 };
14 int main() {
15 child o = parent();
o.display();
16
return 0;
17 }
18
19
There are many more such uses that make C++ a desired language.
Bool is a data type in C++ which takes two values- True and False. Syntax is as follows:
bool b1 = true;
1
2 #include<iostream>
using namespace std;
3
int main()
4 {
5 int a= 60, b= 70;
6 bool c, d;
7 c= a== b; // false
8
c= a< b; // true
9
10
cout <<b1;
11 cout << b2 ;
12
13 return 0;
14 }
15
For limiting the decimal places in C++ there are five functions : floor(), ceil(), trunc(), round() and setprecision(). Out of these
five, only setprecision() function is used for setting the decimal places to put as output. All the functions are mentioned in the
following sample code.
1
2 #include<bits/stdc++.h>
3 using namespace std;
4
int main()
5 {
6 float a =2.33333;
7 cout << floor(a) << endl;
8 cout << ceil(a) << endl;
cout << trunc(a) << endl;
9
cout << round(a) << endl;
10 cout << setprecision(2) << a;
11 return 0;
12 }
13
In C++, there are three functions in the cstdlib header file to return the absolute value of the integer. Those are:
– abs()
– labs()
– llabs()
The difference lies in the range for integer value being passed as an argument. For abs() its type int in C++. For labs(), its type
long int in C++ and for llabs() its long long int in C++.
1 #include <cstdlib>
#include <iostream>
2
3
using namespace std;
4
5 int main()
6 {
7
8 int a, b, c;
9
10 a = abs(22);
11 b= labs(1234355L);
c= llabs(1234863551LL);
12 cout << a;
13 cout << b;
14 cout<< c;
15 return 0;
16 }
17
The strings in C++ can be concatenated in two ways- one considering them string objects and second concatenating them C
style strings.
1 #include <iostream>
using namespace std;
2
3
int main()
4 {
5 string s_1, s_2, fin;
6 cout << "Enter string";
7 getline (cin, s_1);
cout << "Enter string ";
8 getline (cin, s_2);
9 fin= s_1 + s_2;
10 cout << fin;
11
12 char str1[50], str2[50], fin[100];
13
14 cout << "Enter string";
cin.getline(str1, 50);
15
16 cout << "Enter string";
17 cin.getline(str2, 50);
18
19
20
21 strcat(str1, str2);
22
23 cout << "str1 = " << str1 << endl;
24 cout << "str2 = " << str2;
25
26 return 0;
}
27
28
There are three methods for converting char variable to int type variable. These are as follows: – atoi()
– sscanf()
– typecasting
1
2 #include<stdio.h>
3 #include<stdlib.h>
4 int main() {
char *s = "6790";
5 char d = 's';
6 int a,b,c;
7
8 sscanf(s, "%d", &a); // Using sscanf
9 printf("a : %d", a);
10
b = atoi(s); // Using atoi()
11 printf(“b : %d", b);
12
13 c = (int)(d); // Using typecasting
14 printf("c : %d", c);
15
16 return 0;
17 }
18
Using the rand() function we can generate random numbers in C++ within a range.
1 #include <iostream>
#include <random>
2 int main()
3 {
4 int max=100, min=54,i;
5 int range = max - min + 1;
6 for (i=min; i<max;i++)
{
7 int num = rand() % range + min;
8 cout<<num;
9
10 }
11 return 0;
12 }
13
A linear data structure which implements all the operations (push, pop) in LIFO (Last In First Out) order. Stack can be
implemented using either arrays or linked list.The operations in Stack are
– Push: adding element to stack
– Pop: removing element from stack
– isEmpty: returns true if stack is empty
– Top: returns the top most element in stack
Conio.h is a header file used for console input and output operations and is used for creating text based user interfaces.
To find the absolute value in c++, we can use abs() function. The abs() function in C++ returns the absolute value of an
integer number.
1
2 #include <iostream>
#include <cstdlib>
3 using namespace std;
4
5 int main()
6 {
7 int a=3.456;
int x = abs(a);
8 cout << x;
9 return 0;
10 }
11
To exit Turbo C++, use the Quit option under the File Menu, or press Alt + X.
Any object which has an ability to iterate through elements of the range it has been pointing to is called iterator.
:: is called a scope resolution operator which is used to access global variables with the same name as of local variables, for
defining functions outside the class, for accessing static variables, and for referring to a class inside of another class.
When you have written code in the file (notepad),save the file as “hello.cpp.” If you want to write in a file using C++ code,
you can do it using iostream and fstream libraries in C++.
1
2 #include <iostream>
#include <fstream>
3 using namespace std;
4
5 int main () {
6 ofstream file_name;
7 file_name.open ("sample.txt");
file_name<< "Write in the file";
8 file_name.close();
9 return 0;
10 }
11
Alt+Enter is the keyboard shortcut used to maximize (full screen) turbo C++.
An expression is a combination of operators, constants and variables. There seven types of expressions for examples:
A class in C++ is the building block that leads to Object-Oriented programming and is a user-defined data type which holds
data and functions. The syntax to write a class in C++ is as follows:
1
2 class Sample
3 {
// Access specifier
4 private:
5
6 // Data Members
7 string s;
8
9 // Member Functions()
10 void printname()
{
11 cout << s;
12 }
13 };
14
GCC and clang are great compilers if the programmer’s target more portability with good speed.
Intel and other compilers target speed with relatively less emphasis on portability.
1
2 #include<stdio.h>
3 #include<string.h>
4 int main()
{
5 // z has greater ASCII value than g
6 char a[] = "zfz";
7 char b[] = "gfg";
8
9 int r = strcmp(a, b);
10
11 if (r==0)
printf("Strings are equal");
12 else
13 printf("Strings are unequal");
14
15 printf("%d" , r);
16
17 return 0;
18 }
19
1 #include <iostream>
#include <fstream>
2 using namespace std;
3 int main()
4 {
5 ofstream fout;
6 string r;
7
fout.open("test.txt");
8
9
while (fout) {
10 getline(cin, r);
11 if (r == "-1")
12 break;
13 fout << line << endl;
}
14 fout.close();
15
16 ifstream fin;
17 fin.open("test.txt");
18 while (fin) {
19 getline(fin, line);
cout << line << endl;
20
21
22
23 }
fin.close();
24 return 0;
25 }
26
27
Stringstream is a class in c++ which associates a string object with a stream allowing to read from the string as if it were a
stream. Syntax is as follows:
stringstream string_name(str);
clear()
str()
<<
>>
If the program does not have using namespace std; then when you write cout <<; you would have to put std::cout <<; same for
other functions such as cin, endl etc.
1 #include <iostream>
2 int main()
3 {
4 std::cout << "Hello, World!";
return 0;
5 }
6
The length of a string can be calculated by using in-built functions such as length(), size(), strlen() and also by loops (while
and for).
1 #include<iostream>
#include<cstring>
2 using namespace std;
3 main() {
4 string s = "Hi I am Mr X";
5 char arr[] = "Hi I am Mr X";
6 cout << s.length();
cout << s.size();
7 cout <<strlen(arr);
8
9
10
11 char *c = arr;
12 int count = 0;
while(*c != '\0'){
13 count++;
14 c++;
15 }
16 cout << count;
17 count = 0;
for(int i = 0; arr[i] != '\0'; i++){
18 count++;
19 }
20 cout << count;
21 }
22
23
There is an in-built function- length()- in C++ to find the length of the string. The code snippet to find the length of string is
as follows
C language is not an object oriented programming language, so it is a constant attempt of C++ to introduce OOPs. Class is a
user defined data type which defines a blueprint of data type. For example,
class Circle{
public:
float radius;
}
Inline functions are functions used to increase the execution time of a program. Basically, if a function is inline, the compiler
puts the function code wherever the function is used during compile time. The syntax for the same is as follows:
A friend function has the access rights to all private and protected members of the class.
1
2 class Circle{
double radius;
3
4 public:
5 friend void printradius( Circle c );
6 };
7 void printradius(Circle c ) {
8 /* Because printradius() is a friend of Circle,
it can
9 directly access any member of this class */
10 cout << "Radius of circle: " << c.width;
11 }
12
13 int main() {
14 Circle c;
15
// Use friend function to print the radius.
16 printradius( c);
17
18 return 0;
19 }
20
Exceptions are errors that happen during execution of code. To handle them we use throw, try & catch keywords.
1
#include<iostream>
2 #include<vector>
3 using namespace std;
4 int main()
5 {
vector <string> vec_1;
6 vec_1.push_back("sample code");
7 vec_1.push_back("change example");
8 for(vector <string>::iterator i=vec_1.begin();i!
9 =vec_1.end();++i)
10 cout<<*i;
return 0;
11 }
12
A sequence of containers to store elements, a vector is a template class of C++. Vectors are used when managing ever-
changing data elements. The syntax of creating vector.
vector <type> variable (number of elements)
For example:
Scope resolution operator in c++ is denoted by double colon (::). It can be used:
Character constant are members of the character set in which a program is written which is surrounded by single quotation
marks (‘).
A feature that allows functions and classes to operate with generic types that means a function or class can work on different
data types without being rewritten is called template.
1
2 "#include <bits/stdc++.h>
using namespace std;
3 int main()
4 {
5 vector<int> vec{ 1,9,4,3,2,8,5,7};
6
7 sort(vec.begin(), vec.end());
8
9 for (auto x : v)
cout << x << "" "";
10
11 return 0;
12 }
13 "
14
A pure virtual function is a type of virtual function which does not have implementation, but is only declared. It is declared by
assigning 0 in declaration. Syntax for the same is as follows:
1 class Test
2 {
3 // Data members of class
4 public:
5
6 virtual void show() = 0;
7
/* Other members */
8 };
9
78. How to use map in C++?
Associative containers storing a combination of a key value or mapped value is called Maps. Syntax: map<key_type ,
value_type> map_name;
1
2 #include <iostream>
3 #include <iterator>
#include <map>
4
5 using namespace std;
6
7 int main()
8 {
9 map<int, int> test;
10
11 // inserting elements
test.insert(pair<int, int>(1, 2));
12 test.insert(pair<int, int>(2, 3));
13
14 map<int, int>::iterator itr;
15 for (itr = test.begin(); itr != test.end(); +
16 +itr) {
cout << itr->first
17
cout << itr->second << '\n';
18 }
19 return 0;
20 )
21
Std::vector::empty tests whether a vector is empty or not. A sample code for illustrating the same is as follows:
1 #include <iostream>
#include <vector>
2
3
int main ()
4 {
5 std::vector<int> vec;
6 int add (0);
7
8 for (int i=1;i<=5;i++) vec.push_back(i);
9
while (!vec.empty())
10 {
11 add+= vec.back();
12 vec.pop_back();
13 }
14
15 std::cout << add;
16
return 0;
17 }
18
19
20
C++ is a standardized language and Visual C++ is a product that implements the standard of C++. One can write portable C++
programs using Visual C++, but one can also use Microsoft-only extensions which destroys portability but enhances your
productivity.
Segmentation fault indicates an error memory corruption. In layman terms, when a piece of code tries to do read and write
operation in a read only location in memory. Below are the reasons and solutions for segmentation error:
1
2 Reason: Accessing an address that is freed
int* p = malloc(8);
3 *p = 100;
4
5 free(p);
6 *p = 110;
7
8 Solution: Before freeing the pointer check the assignment or any operation
9 required to perform.
10
Reason: Accessing out of array index bounds
11 int arr[2];
12 arr[3] = 10;
13 Solution: Correcting the array bound
14
15 Reason: Improper use of scanf()
16 int n = 2;
scanf("%d",n);
17 Solution: To avoid this is the only solution
18
19 Reason: Dereferencing uninitialized pointer
20 int *p;
21 printf("%d",*p);
Solution: A pointer must point to valid memory before accessing it.
22
23
Reason: Stack Overflow
24 Solution: It can be resolved by having a base condition to return from the
25 recursive function.
26
STL in C++ is a library and abbreviation of Standard Template Library. STL is a generalized library that provides common
programming data structures/ container classes, functions, algorithms, and iterators. STL has four components
– Algorithms: Searching and sorting algorithms such as binary search, merge sort etc.
– Containers: Vector, list, queue, arrays, map etc.
– Functions: They are objects that act like functions.
– Iterators: It is an object that allows transversing through elements of a container, e.g., vector<int>::iterator.
83. What is flush in C++?
std::flush synchronizes the stream buffer with its controlled output sequence.
1 string str_1;
2 cout << "Enter the string";
3 cin >> str_1;
Way 2:
1 string str_1;
2 cout << "Enter the string";
3 getline (cin, str_1)
A function is said to be virtual if it is defined in base class and is expected to be redefined in derived class.
1
2 #include <iostream>
3 using namespace std;
4
5 class Base_Class {
public:
6 virtual void print_msg() {
7 cout << "Base";
8 }
9 };
10
class Derived_Class : public Base_Class {
11
public:
12 void print_msg() {
13 cout << "Derived";
14 }
15 };
16
1
#include <iostream>
2 using namespace std;
3
4 void main()
5 {
6 int a[] = {0,1,2,3,4,5};
7 int a_size = sizeof(a)/sizeof(a[0]);
cout << ""Size of the array is: "" << a_size;
8 }
9 "
10
There are 2 approaches to convert integer variables to string. Both the approaches with a sample code are mentioned below.
Approach 1:
1
#include<iostream>
2 #include<string>
3 using namespace std;
4 void main()
5 {
6 int n= 1;
string s= to_string(n);
7 cout << s;
8 }
9
Approach 2:
1
2 #include<iostream>
3 #include <sstream>
4 #include <string>
5 using namespace std;
int main()
6 {
7 int n = 17;
8
9 // declaring output string stream
10 ostringstream s1;
11
12 // Sending a number as a stream into output str
s<< n;
13 // the str() converts number into string
14 string fin = s.str();
15 // Displaying the string
16 cout << fin;
17 return 0;
}
18
19
89. How to sort a string in C++?
To sort a string, the sort function in c++ can be used. The sample code for the same is as follows.
1
2 #include<iostream>
3 #include <stdio.h>
4 using namespace std;
5 void str_sort(string &s)
{
6 sort(s.begin(), s.end());
7 cout << s;
8 }
9
10 int main()
{
11
string s = ""anmbdfc"";
12 str_sort(s);
13 return 0;
14 }
15
16 Output: abcdfmn
"
17
18
1
2 int main()
{
3 string str_value = "1122";
4 int int_value = stoi(str_value);
5 }
6 or
7 int main()
{
8 const char *str_ptr = "1122";
9 int int_value = atoi(str_value);
10 }
11
Two string can be compared using strcmp() function. It return boolean value; if it returns ‘0’ then the strings are same and if it
returns ‘1’ then the two strings are not same.
1 int main()
2 {
3 if (strcmp(str_value_a, str_value_b) == 0)
cout<<"These strings are the same";
4 else
5 cout<<"These strings are not the
6 same";
7 }
92. How to set precision in C++?
Precision in C++ can be set by using the following functions- floor(), ceil(), round(), trunc() and setprecision(). Using
setprecision() in a program.
1
#include<bits/stdc++.h>
2 using namespace std;
3
4 void main()
5 {
6 double p = 8.04149;
cout << fixed << setprecision(2) << pi<<endl;
7
}
8
9 The output will be 8.04.
10
Using this pointer, every object is provided access to its own address. It is an implicit parameter to all member functions.
Only member functions have a this pointer and not a friend function.
1
2
3 #include<iostream>
4 using namespace std;
5
class sample
6 {
7 private:
8 int a;
9 public:
10 void set_var (int a)
{
11 this->a = a;
12 }
13 void print()
14 {
cout << x ;
15
}
16 };
17
18 int main()
19 {
20 sample obj;
int a = 2;
21 obj.set_var(a);
22 obj.print();
23 return 0;
24 }
25
26
1 "#include <iostream>
2
using namespace std;
3 int main
4 {
5 string str_a = ""Hi, My name is"";
6 string str_b = ""Raj"";
7 string str_c = str_a + str_b;
cout<<""The string is:""<<str_c;
8 return 0;
9 }"
10
1 int main()
2 {
3 string str[]=""Hello World!"";
4 int g = str.size();
5 cout<<""The size of the string is""<<g;
}
6 or you can use the strlen function."
7
1 "int main()
2 {
3 string yourname;
4 getline (cin,yourname);
5
}"
6
You can use the cin function to take in values, like such:
1 int main()
{
2 int age;
3
cout<<""Enter your name!"";
4 cin>>age;
5 }"
6
1 "int main()
2 {
3 string str_value[]=""Hello-World!"";
4 cout<<""The string is:""<<str_value;
}"
5
1 "syntax: sort(the element of the array from where you want to start the sorting,the ele
2 to finish the sorting )
3 int main()
{
4 int int_value[5]={1,2,3,4,5};
5 sort(intr_value,intr_value+5);
6 cout<<intr_value;
7 }"
syntax: reverse(the index you want to start reversing at,the index you want to end reversing at)
vector<int> value = {11,22,33};
reverse(value.begin(),value.end());
1 "#include<iostream>
#include<vector>
2
3
using namespace std;
4
5 vector<int> fun(vector<int> value_c)
6 {
7 vector<int> value_d;
8 for(int j=0;j<value_c.size();j++)
9
value_d.push_back(value_c[j]+4);
10
11 return value_d;
12 //returning the vector
13 }
14
15 int main()
16 {
17
vector<int> value_a,value_b;
18
19
//We put values in vector value_a
20
21
22 value_a.push_back(1);
23 value_a.push_back(2);
value_a.push_back(3);
24
25
26 value_b = fun(value_a);
27 //receiving the vector
28
29 return 0;
30 } "
31
32
1
2
"#include<iostream>
3 using namespace std;
4
5 int main()
6 {
7 int n;
8 cin >> n;
int a[n];
9 int i;
10 for(i = 0; i < n; i++)
11 {
12 cin >> arr[i];
}
13 for(i = n-1; i >= 0; i--)
14 {
15 cout << arr[i] << ” “;
16 }
17 cout << endl;
return 0;
18
19
}
20 "
21
22
1 "#include <stdio.h>
#include <string.h>
2
3
int main ()
4 {
5 char * flag_pointer;
6 char string_value[10]=""Great Learning!"";
7 flag_pointer =strtok (string_value,"" !"");
8
while (flag_pointer!=NULL)
9
10
11 {
12 cout<<string_value;
flag_pointer=strtok(NULL,"" !"");
13 }
14
15 return 0;
16 }"
17
To sort a string, the sort function in c++ can be used. The sample code for the same is as follows.
1
2 #include<iostream>
3 #include <stdio.h>
4 using namespace std;
5 void str_sort(string &s)
{
6 sort(s.begin(), s.end());
7 cout << s;
8 }
9
10 int main()
{
11
string s = ""anmbdfc"";
12 str_sort(s);
13 return 0;
14 }
15
16 Output: abcdfmn
"
17
18
Constructor is a method in class which has the same name as that of class and is followed by parentheses (). It is automatically
called when an object of a class is created.
Just like a child inherits some features and attributes from his parent similarly a class inherit attributes and methods from
another class. The parent class is called base class and the child class is called derived class.
1
// Base class
2 class Food_Item{
3 public:
4 void taste() {
5 cout << ""The taste of every food item is
6 different. \n"" ;
7 }
};
8
9 // Derived class
10 class Chips: public Food_Item{
11 public:
12 void taste() {
cout << ""The taste of chips is salty \n"" ; }
13 };
14 "
15
Class in C++ provides a blueprint for object, that means, object is created from the class.
1 For example,
2 class Circle{
3
4 public:
5 float radius;
6 }
7
Circle C1;
8 Circle C2;
9
To prevent access to data directly, Encapsulation is the process that combines data variables and functions in a class. This is
achieved by doing the following:
Abstraction in C++ means showing only what is necessary. It’s part of Object oriented Programming concept. Abstraction is
used to hide any irrelevant data to the outside world and only showing what is absolutely necessary for the outside world to
use.
eg. Classes use the abstraction concept to only show relevant data types or elements. This is done through access specifiers
such as: public, private, protected.
OOP or Object Oriented Programming in C++ is a type of programming in which you create objects and classes to emulate
real world concepts such as Abstraction, Polymorphism, Encapsulation, Inheritance.
Here classes are data types that allow you list several types of data within it and even functions. You can access these classes
with the help of class objects.
Member functions are those functions that you declare within a class, they are members of the class. You can reference them
using class objects. Eg.
1
class A
2 {
3 public:
4 int add(int b)
5 {
6 a = b * 10;
return a;
7 };
8 };"
9
Here Z may inherit similar features from X & Y as they both have inherited them from W. This can cause issues and that’s
why we use virtual base classes as they stop multiple features of a class from appearing in another class.
Private members of the class are not accessible by object or function outside the class. Only functions inside the class can
access them or friend functions. However, pointers can be used to access private data members outside the class. Sample code
is as follows:
1 #include <iostream>
using namespace std;
2
3
class sample_test{
4 private:
5 int n;
6
7 public:
8 sample_test() { n = 45; }
9
10 int display() {
return n;
11 }
12 };
13
115. How to call base class constructor from derived class in C++?
A base class constructor will be called whenever the derived class constructor is called. Upon the creation of a dervied class
object the order of constructor execution is : base class constructor then Default class constructor.
An abstract class in C++ is such that cannot be used directly and is used to form a base class for others to inherit from.
If you create an object for an abstract class the compiler will throw an error at you.
Containership in C++ is a relationship in which a class’s object is nested within another class. The class that contains the
object is called a container class and the class whose object is stored is called a contained class.
An object oriented technique of hiding data members is called data hiding. In other words, giving restricted access to the data
members so as to maintain object integrity.
1 #include <bits/stdc++.h>
using namespace std;
2
3
class parent
4 {
5 public:
6
7 void print()
8 { cout<< ""base class""; }
};
9
10
class child:public parent
11 {
12 public:
13
14 void print()
15 { cout<< ""derived class""; }
};
16
17
int main()
18 {
19 parent *p;
20 child c;
21
22 p = &c;
23
24 //virtual function, binded at runtime (Runtime
25 polymorphism)
26 p->print();
27 return 0;
}
28 "
29
30
A copy constructor is a constructor which creates an object by initializing it with an object of the same class, which has been
created previously. The syntax for copy constructor is as follows:
Modularity is a way of mapping encapsulated abstractions into real and physical modules which is closely related to
Encapsulation. It is a concept in which separate programs are divided into separate modules.
For example, when building a house it is built in modular way. First foundation is laid, then structure is made and so on.
Size of an empty class is 1 byte generally just to ensure that the two different objects will have different addresses.