C++ Basic Questions
1. what are C++ Modifier?How many types are there.
We have basic data types like int, char, double. A modifier is used to change the property of the base type.
There are four kinds of modifiers:
- signed
- unsigned
- short
- long
* All four modifiers can be applied to the int type
* char type allows only signed and unsigned modifiers
* double type can be used with the long modifier
2. How to call C functions from C++?
you can use ” extern “C” ” syntax.
Method 1:
extern “C” void foo(int);
Method 2:
extern “C”
{
void foo(int);
//more declarations…
}
3. What is the ellipsis catch handler in C++? Explain with an example.
Ellipsis catch handler is used to catch any unhandled exceptions. So it acts as a default handler when no other handlers are appropriate.
Example:
try
{
throw “Something”;
}
// the ellipsis catch handler:
catch(…)
{
cout << “This is a default handler”;
}
4. Difference between reference and pointer in C++.
- A pointer can be re-assigned any number of times while a reference cannot be re-assigned after binding.
- Pointers can point nowhere (NULL), whereas a reference always refers to an object.
- You can’t take the address of a reference like you can with pointers.
- There’s no “reference arithmetic” (but you can take the address of an object pointed by a reference and do pointer arithmetic on it as in &obj + 5).
- You can have pointers to pointers offering extra levels of indirection. Whereas references only offer one level of indirection.
- References can be used in function parameters and return types.
5. Difference between exit abort and assert functions in C++
exit():
syntax:
void exit(int status_value);
exit() is used to terminate the calling function immediately without executing further processes.
exit() performs following operations.
* Flushes unwritten buffered data.
* Closes all open files.
* Removes temporary files.
* Returns an integer exit status to the operating system.
abort():
syntax:
void abort(void);
abort() may not close files that are open.
It may also not delete temporary files and may not flush stream buffer.
It does not call functions registered with atexit().
assert():
syntax :
void assert(int exp);
If expression evaluates to 0 (false), then the expression, source code filename, and line number are sent to the standard error, and then abort() function is called.
6. Difference between C Structure and C++ Structure?
C Structures
- Structures in C cannot have member functions inside structure.
- We cannot directly initialize structure data members in C but we can do it in C++.
- In C, we need to use struct to declare a struct variable
- C structures cannot have static members but is allowed in C++.
- Structures in C cannot have constructor inside structure but Structures in C++ can have Constructor creation.
- sizeof operator will generate 0 for an empty structure in C whereas 1 for an empty structure in C++.
- C structures do not allow concept of Data hiding but is permitted in C++ as C++ is an object oriented language whereas C is not.
- Structure in C can’t have static members, but C++ structure can have static members.
C++ Structures
- Structures in C++ can have member functions along with data members.
- Members of a class are private by default and members of a struct are public by default.
- In C++, struct is not necessary.
7. Different types of linkages available in C++ explain.
There are 3 types of linkages in C++
extern linkage: variable is visible in all files
internal linkage: variable is visible in single file.
No linkage : identifiers can only be seen in the scope in which they are defined.
Additional Information
* global variable is external linkage
* const global variable is internal linkage
* extern const global variable is external linkage
8. What is stack unwinding in C++
- As you create objects statically (on the stack as opposed to allocating them in the heap memory) and perform function calls, they are “stacked up”.
- When a scope (anything delimited by { and }) is exited (by using return XXX;, reaching the end of the scope or throwing an exception) everything within that scope is destroyed (destructors are called for everything).
- This process of destroying local objects and calling destructors is called stack unwinding.
9. Different ways to initialize a variable in C++
Method 1: Traditional Method using C notation.
int result = 10;
Method 2: Using the constructor notation.
int result (10);
10. Different parameter Passing Techniques in C/C++
1. Pass By Value :
#include <iostream>
using namespace std;
void func(int a, int b)
{
a += b;
printf(“In func, a = %d b = %d\n”, a, b);
}
int main(void)
{
int x = 5, y = 7;
// Passing parameters func(x, y);
printf(“In main, x = %d y = %d\n”, x, y);
return 0;
}
2. Pass by reference(aliasing)
#include <iostream>
using namespace std;
void swapnum(int* i, int* j)
{
int temp = *i;
*i = *j;
*j = temp;
}
int main(void)
{
int a = 10, b = 20;
// passing parameters swapnum(&a, &b);
printf(“a is %d and b is %d\n”, a, b);
return 0;
}
11. Is String primitive data type in C++?
No, it’s a class from STL (Standard template library).
12. We can have global and local variables with same name?
Yes, we can access with scope resolution operator i.e ::.
#include<iostream.h>
int num = 10;
int main()
{
int num = 2;
cout<<”Global Variable num = “<<::num;
cout<<”\nlocal Variable num = “<<num;
}
13. What is the difference between delete and delete[] in C++
“delete[]” is used to release the memory allocated to an array which was allocated using new[].
“delete” is used to release one chunk of memory which was allocated using new.
14. What is a Reference Variable in C++
A reference variable is an alias for already existing variable.
It means, the reference variable and the variable name, both point ot the same memory location.
Example:
int num1 =10;
int &num2 = num1;
15. what are default arguments in C++?
A default argument will be provided during the function declaration. If the caller function doesn’t provide the value for that argument, the compiler will automatically assign this default argument.
Example:
#include<iostream>
using namespace std;
int sum(int x, int y, int z=0)
{
return (x + y + z);
}
int main()
{
// we did not assign 3rd argument, then compiler will take it as 0
cout << sum(101, 115) << endl;
cout << sum(101, 115, 25) << endl;
return 0;
}
16. what are storage class? List them .
Storage Class determines the life or scope of a variable.
There are 5 different storage class:
- Auto
- Static
- Extern
- Register
- Mutable
17. what is mutable storage class?
When you create an object of a class as constant, but you need to modify any one data member, then you need to declare that data member as mutable.
Example:
class A
{
public:
A (int a, int b)
{
x = a;
y = b;
}
mutable int x;
int y;
};
int main()
{
const A var1;
var1.x = 35;
// var1.y = 25; // uncommenting this line will result in compiler error
}
18. What is Name Mangling in C++?
- We know that C++ supports function overloading. It means, there can be more than one function with same name, but with different parameters.
- But how does C++ distinguish between the functions when it generates the code?
- It changes the name by additionally adding information about the arguments, this process is called as name mangling.
For example:
If the functions are declared as below:
int fun (void) { return 1; }
int fun (int) { return 0; }
C++ can mangle the name as below:
int __fun_v (void) { return 1; }
int __fun_i (int) { return 0; }
19. What is the difference between Method Overloading and Method Overriding in C++?
Method Overloading:
* Method overloading is having functions with the same name but different arguments
* This is a form of compile-time polymorphism.
Example:
void area(int a);
void area(int a, int b);
Method Overriding:
It is the redefinition of base class function in its derived class with same signature i.e return type and parameters.
It can only be done in derived class.
Example:
Class a
{
public:
virtual void display(){ cout << “hello”; }
}
Class b:public a
{
public:
void display(){ cout << “bye”;};
}
20. what operators cannot be overloaded?
?: (conditional)
. (member selection)
.* (member selection with pointer-to-member)
:: (scope resolution)
sizeof (object size information)
typeid (object type information)
static_cast (casting operator)
21. what are the uses of Scope resolution operator?
1) To access a global variable when there is a local variable with same name:
2) To define a function outside a class.
3) To access a class’s static variables.
4) In case of multiple Inheritance: If same variable name exists in two ancestor classes, we can use scope resolution operator to distinguish.
5) For namespace
std::cout << “Hello” << std::endl;
6) Refer to a class inside another class.
22. How can I modify my own C header files so it’s easier to #include them in C++ code?
- If you are including a C header file that isn’t provided by the system, and if you are able to change the C header, you should strongly consider adding the extern “C” {…} logic inside the header to make it easier for C++ users to #include it into their C++ code.
- Since a C compiler won’t understand the extern “C” construct, you must wrap the extern “C” { and } lines in an #ifdef so they won’t be seen by normal C compilers.
Example:
#ifdef __cplusplus
extern “C” {
#endif
//function prototype declarations
#ifdef __cplusplus
}
#endif
23. what kind of functions cannot be overloaded in C++?
1. Function declarations that differ only in the return type.
int foo()
{
return 10;
}
char foo()
{
return ‘a’;
}
2. Member function declarations with the same name and the name parameter-type-list cannot be overloaded if any of them is a static member function declaration.
class Test
{
static void fun(int i) {}
void fun(int i) {}
};
3. Two parameter declarations that differ only in their default arguments are equivalent.
int f ( int x, int y)
{
return x+10;
}
int f ( int x, int y = 10)
{
return x+y;
}
4. Parameter declarations that differ only in the presence or absence of const and/or volatile are equivalent.
int f ( int x)
{
return x+10;
}
int f ( const int x)
{
return x+10;
}
5. Parameter declarations that differ only in a pointer * versus an array [] are equivalent.
int fun(int *ptr);
int fun(int ptr[]); // redeclaration of fun(int *ptr)
24. Can main() be overloaded in C++?
Consider the below example:
#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;
return 0;
}
int main()
{
main(3);
main(“C++”);
main(9, 6);
return 0;
}
If you compile it, it will throw an error.
To solve this, it is necessary to use class and declare the main as member function.
#include <iostream>
using namespace std;
class Test
{
public:
int main(int s)
{
cout << s << “\n”;
return 0;
}
int main(char *s)
{
cout << s << endl;
return 0;
}
int main(int s ,int m)
{
cout << s << ” ” << m;
return 0;
}
};
int main()
{
Test obj;
obj.main(3);
obj.main(“I love C++”);
obj.main(9, 6);
return 0;
}
This will work because, in C++ “main” is not a keyword.
25. Is it ok to write “void main()” or “main()” in C/C++?
void main() { /* … */ } is not there standard in C++
Only
int main() { /* … */ }
int main(int argc, char* argv[]) { /* … */ }
are valid standard in C++.
Point to be taken, that both of the functions return an int value.
The int returned by main() is a way for a program to return a value to “the system” that invokes it.
26. Difference between exit() and return() in C++
When you return from a function, destructor will be called.
When you exit from a function, destructors for locally scoped non-static objects are not called.
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
using namespace std;
class Test
{
public:
Test()
{
printf(“Inside Test’s Constructor\n”);
}
~Test()
{
printf(“Inside Test’s Destructor”);
}
};
int main()
{
Test t1;
// using exit(0) to exit from main
exit(0);
}
Output:
Inside Test’s Constructor
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
using namespace std;
class Test
{
public:
Test()
{
printf(“Inside Test’s Constructor\n”);
}
~Test()
{
printf(“Inside Test’s Destructor”);
}
};
int main()
{
Test t1;
return(0);
}
Output :
Inside Test’s Constructor
Inside Test’s Destructor
27 . How to print “Hello World” with empty or blank main in C++
Method 1:
By creating a global variable
#include <bits/stdc++.h>
int x = printf(“Hello World”);
int main()
{
// Blank
}
Method 2:
We can use Constructor in C++.
#include <iostream>
using namespace std;
class A {
public:
A() // Constructor
{
cout << “Hello World”;
}
};
A obj; // Create Object of class A
int main()
{
// Blank
}
28. Example for for_each loop
Syntax for for_each loop:
for_each (InputIterator first, InputIterator last, Function fn)
first : The beginning position from where function operations has to be executed.
last : This ending position till where function has to be executed.
fn : The 3rd argument is a function or an object function which operation would be applied to each element.
Example:
#include<iostream>
#include<algorithm>
using namespace std;
void myFun(int x)
{
cout << x << ” “;
}
struct myClass // object type function
{
void operator() (int x)
{
cout << x << ” “;
}
} obj1;
int main()
{
int arr[] = {1, 2, 4, 3};
// passing simple function for_each(arr, arr + 4, myFun);
cout << endl;
// passing object type function
for_each(arr, arr + 4, obj1);
return 0;
}
Output:
1 2 4 3
1 2 4 3
29. Generate random numbers in C++
rand() is used to generate random numbers in C++.
srand() is used to set seed which is used by rand().
If we set the seed(1), then the output will be same on every program run.
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
int main()
{
srand(1);
for(int i=0; i<5; i++)
cout << rand() % 100 <<” “;
return 0;
}
Output:
83 6 74 23 65
To get different random number every time, then set srand(time(NULL)) should be used.
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
int main()
{
srand(time(NULL));
for(int i=0; i<5; i++)
cout << rand() % 100 <<” “;
return 0;
}
Output:
34 62 53 67 98
Now for every run, we get different random number.
To get random number in specific range, then use below formula:
int min = 50;
int max = 150;
min + (rand() % (int)(max – min + 1))
30. Explain string class in C++
To use string class, include below header:
#include <string>
Below are the constructors available in C++ string class:
* string () : creates an empty string (“”)
* string ( other_string ) : creates a string identical to other_string * string ( other_string, position, count ) : creates a string that contains count characters from other_string, starting at position. If count is missing (only the first two arguments are given), all the characters from other_string, starting at position and going to the end of other_string, are included in the new string.
* string ( count, character ) : create a string containing character repeated count times
Constant Member Functions:
These functions do not modify the string.
unsigned int length () : returns the length of the string
unsigned int size () : returns the length of the string (i.e., same as the length function)
bool empty () : returns true if the string is empty, false otherwise
Operators Defined for string:
Assign =
————–
string s1;
string s2;
…
s1 = s2; // the contents of s2 is copied to s1
Append +=
————–
string s1( “abc” );
string s2( “def” );
…
s1 += s2; // s1 = “abcdef”
Concatenate +
————–
string s1( “abc” );
string s2( “def” );
string s3;
…
s3 = s1 + s2; // s3 = “abcdef”
Equality ==
————–
string s1( “abc” );
string s2( “def” );
string s3( “abc” );
…
bool flag1 = ( s1 == s2 ); // flag1 = false
bool flag2 = ( s1 == s3 ); // flag2 = true
Some of Member Functions available:
void swap ( other_string ) : swaps the contents of this string with the contents of other_string.
string & append ( other_string ) : appends other_string to this string, and returns a reference to the result string.
unsigned int find ( other_string, position ) : finds other_string inside this string and returns its position. If position is given, the search starts there in this string, otherwise it starts at the beginning of this string.
string substr ( position, count ) : returns the substring starting at position and of length count from this string
31. What are inline functions in C++?
If a function is made inline, the compiler places a copy of the code of that function at each point where the function is called at compile time.
If you make a function inline, you need to recompile the program, because compiler needs to all the code once again.
There are 2 ways to make a function inline.
Method 1:
Write the definition of member function inside the body of class declaration.
class MyClass
{
public:
//an inline function
string myCLassName()
{
return “My Class”;
}
};
Method 2:
Use “inline” keyword.
inline int Max(int a, int b)
{
return (a > b)? a : b;
}
32, Example program for enum in C++
Method 1: Declare enum variable while creating an enum.
#include<iostream>
using namespace std;
enum direction {
East,
West,
North,
South
}dir;
int main()
{
dir = East;
cout<<dir;
return 0;
}
Method 2: Declare enum variable.
#include<iostream>
using namespace std;
enum direction {
East,
West,
North,
South
};
int main()
{
direction dir;
dir = East;
cout<<dir;
return 0;
}
33. Example for Reference to Function
Consider you have a function as below:
int foo(double i)
{
return 2;
}
To create a reference to a function you have to use the following syntax:
type (&identifier) (parameter list) = referenced function;
In our example, reference to a function can be created by:
int(&referenceToFunction)(double) = foo; and can be called by:
referenceToFunction(4.0);
34. Example for Reference as a Parameter of a Function
Consider the below function:
void negative(int& a)
{
//make a as negative
a *= (-1);
}
Calling:
int k = 10;
cout << “k before function call ” << k << endl;
opposite(k);
cout << “k after function call ” << k << endl;
Output:
k before function call 10
k after function call -10
35. Explain Const function
A const or a constant member function can only read or retrieve the data members of the calling object without modifying them.
The syntax for defining a const member function is
return_type function_name (parameter_list) const
{
//body of the member function
}
Example:
#include<iostream>
using namespace std;
class Test
{
int value;
public:
Test(int v = 0) {value = v;}
int getValue() const {return value;}
};
int main()
{
Test t(20);
cout<<t.getValue();
return 0;
}
When a function is declared as const, it can be called on any type of object. Non-const functions can only be called by non-const objects.
36. Explain Static function
Static member functions are used to maintain a single copy of a class member function across various objects of the class.
Restrictions on static member functions are :
1. They can directly refer to other static members of the class.
2. Static member functions do not have this pointer.
3. Static member function cannot be virtual.
Example:
#include <iostream>
using namespace std;
class MyClass
{
static int i;
public:
static void init(int x)
{
i = x;
}
void show()
{
cout <<i; }
};
int MyClass::i;
int main()
{
MyClass::init(100); //initialize static variable i before creating object
MyClass x;
x.show();
return 0;
}
37. Guess the output of the program 1
#include<iostream>
using namespace std;
int &fun()
{
int x = 20;
return x;
}
int main()
{
fun() = 40;
cout << fun();
return 0;
}
Output:
Runtime error
Why?
Since we return reference to a local variable, the memory location becomes invalid after function call is over.
Might result in segmentation fault.
38. Guess the output of the program 2
#include<iostream>
using namespace std;
int &fun()
{
static int x = 110;
return x;
}
int main()
{
fun() = 130;
cout << fun();
return 0;
}
Output:
130
Why?
Notice that x is a static variable, the function call fun() = 130, modifies x to 130. Hence next call “cout << fun()” returns the modified value.
39. Guess the output of the program 3
#include<iostream>
using namespace std;
int main()
{
int x = 10;
int &ref = x;
ref = 120;
cout << “x = ” << x << endl ;
x = 130;
cout << “ref = ” << ref << endl;
return 0;
}
Output:
x = 120
ref = 130
Why?
ref is an alias of x. Hence changing one, will change other also.
40. Different ways to convert int to string in C++
1:
int a = 20;
char *intStr = itoa(a);
string str = string(intStr);
2:
int a = 12;
stringstream ss;
ss << a;
string str = ss.str();
operator << — add a string to the string stream object
3:
#include <string>
std::string s = std::to_string(452);
41. What is the “–>” operator in below code?
#include <stdio.h>
int main()
{
int x = 10;
while (x –> 0)
{
printf(“%d “, x);
}
}
–> is not an operator. It is in fact two separate operators, — and >.
The statement could be written as follows:
while( (x–) > 0 )
42. What is The Rule of Three?
If your class needs any of
a copy constructor,
an assignment operator,
or a destructor,
defined explicitly, then it is likely to need all three of them.
43. Why is “using namespace std;” considered bad practice?
Consider you are using two libraries called Foo and Bar:
using namespace foo;
using namespace bar;
You call Blah() from Foo and Qix() from Bar without problems.
Then you upgrade to a new version of Foo 2.0, and offer a function called Qix (). Now Both Foo 2.0 and Bar import Qix () into your global namespace.
This is going to take some effort to fix, especially if the function parameters happen to match.
But If you had used foo::Blah() and bar:: Qix (), then the introduction of foo:: Qix () would have been a non-event.
Constructor and Destructor Questions
44. What is the need for virtual destructors in C++
Deleting a derived class object using a pointer to a base class that has a non-virtual destructor results in undefined behaviour.
To correct this situation, the base class should be defined with a virtual destructor.
Example: Without virtual destructor
#include<iostream>
using namespace std;
class base
{
public:
base()
{
cout<<“Constructor of base class \n”;
}
~base()
{
cout<<“Destructor of base class \n”;
}
};
class derived: public base
{
public:
derived()
{
cout<<“Constructor of derived class\n”;
}
~derived()
{
cout<<“Destructor of derived class \n”;
}
};
int main(void)
{
derived *d = new derived();
base *b = d;
delete b;
return 0;
}
Output:
Constructor of base class
Constructor of derived class
Destructor of base class
As you can see from the output above, destructor of derived class is not called. Hence making the base class destructor as “virtual” will make sure that object of derived class is destroyed properly.
Example: With virtual destructor
#include<iostream>
using namespace std;
class base
{
public:
base()
{
cout<<“Constructor of base class \n”;
}
virtual ~base()
{
cout<<“Destructor of base class \n”;
}
};
class derived: public base
{
public:
derived()
{
cout<<“Constructor of derived class\n”;
}
~derived()
{
cout<<“Destructor of derived class \n”;
}
};
int main(void)
{
derived *d = new derived();
base *b = d;
delete b;
return 0;
}
Output:
Constructor of base class
Constructor of derived class
Destructor of derived class
Destructor of base class
45. What is a constructor, explain with an example
- Constructor is a special type of member function whose name is same as class name.
- Usually constructor is used to initialize a data member.
- Constructors don’t have return type
- A constructor is automatically called when an object is created.
- If you don’t declare a constructor, compiler will automatically create one.
There are 2 type of constructor:
1. Default constructor:
These type of constructor will not accept any parameter. This constructor will be called automatically when an object is created.
#include <iostream>
using namespace std;
class construct
{
public:
int a;
// Default Constructor
construct()
{
a = 10;
}
};
int main()
{
construct c;
cout << “a: ” << c.a << endl
return 0;
}
2. Parameterized Constructors:
In these type of constructor, they will accept arguments.
These arguments will help in initializing the data members when objects are created.
Example:
#include <iostream>
using namespace std;
class Point {
private:
int x, y;
public:
// Parameterized Constructor
Point(int x1)
{
x = x1;
}
int getX()
{
return x;
}
};
int main()
{
// Constructor called
Point p1(10);
// Access values assigned by constructor
cout << “p1.x = ” << p1.getX();
return 0;
}
Whenever we define one or more Parameterized constructors for a class, a default constructor should also be explicitly defined as the compiler will not provide a default constructor in this case.
46. What is a copy constructor?
A copy constructor is a member function which initializes an object using another object of the same class.
Default constructor does only shallow copy.
Deep copy is possible only with user defined copy constructor.
Example:
#include <iostream>
using namespace std;
class A
{
public:
int x;
// parameterized constructor.
A(int a)
{
x=a;
}
// copy constructor
A(A &i)
{
x = i.x;
}
};
int main()
{
// Calling the parameterized constructor.
A a1(20);
// Calling the copy constructor.
A a2(a1);
cout<<a2.x;
return 0;
}
47. Can constructor be private in C++?
Yes, you can create a constructor a private.
But if you make a constructor of a class as private, that class cannot be instanciated.
But we have a workaround for it:
You can access it through friend class.
#include <iostream>
using namespace std;
// class A
class A
{
private:
A()
{
cout << “constructor of A\n”;
}
friend class B;
};
// class B, friend of class A
class B
{
public:
B()
{
A a1; cout << “constructor of B\n”;
}
};
int main(){
B b1;
return 0;
}
48. What is a destructor?
A destructor is a special member function that is used to delete the object.
When destructor will be called?
Destructor will be automatically called in below scenarios:
1. When object goes out of scope.
2. Delete operator is called
3. Program ends
4. block containing local variable is called.
Additional Points:
Destructors have same name as the class preceded by a tilde (~)
Destructors don’t take any argument and don’t return anything
Example:
#include <iostream>
using namespace std;
class HelloWorld
{
public:
//Constructor
HelloWorld()
{ cout<<“Constructor is called”<<endl;
}
//Destructor
~HelloWorld()
{
cout<<“Destructor is called”<<endl;
}
};
int main()
{
//Object created
HelloWorld obj;
return 0;
}
Output:
Constructor is called
Destructor is called
49. Can constructor be overloaded?
Yes constructor can be overloaded.
Overloaded constructor will have same name and different arguments.
Example:
#include <iostream>
using namespace std;
class construct
{
public:
float area;
// Constructor with no parameters
construct()
{
area = 0;
}
// Constructor with two parameters
construct(int a, int b)
{
area = a * b;
}
void disp()
{
cout<< area<< endl;
}
};
int main()
{
construct ctr1;
construct ctr2( 20, 40);
ctr1.disp();
ctr2.disp();
return 1;
}
Output:
0
800
50. Can destructor be overloaded? Give explanation.
- No a destructor can never be overloaded in C++.
- An overloaded destructor would mean that the destructor has taken arguments.
- Since a destructor does not take arguments, it can never be overloaded.
51. What is shallow copy and deep copy?
- Shallow Copy A shallow copy of an object copies all of the member field values.
- This works well if the fields are values, but may not be what you want for fields that point to dynamically allocated memory.
- The pointer will be copied. but the memory it points to will not be copied — the field in both the original object and the copy will then point to the same dynamically allocated memory.
- The default copy constructor and assignment operator make shallow copies.
Deep Copy
- A deep copy copies all fields, and makes copies of dynamically allocated memory pointed to by the fields.
- To make a deep copy, you must write a copy constructor and overload the assignment operator, otherwise the copy will point to the original, with disastrous consequences.
- A class that requires deep copies generally needs:
- A constructor to either make an initial allocation or set the pointer to NULL.
- A destructor to delete the dynamically allocated memory.
- A copy constructor to make a copy of the dynamically allocated memory.
- An overloaded assignment operator to make a copy of the dynamically allocated memory.
52. Is it possible for a constructor to throw an error?
Throwing exceptions in the constructor is standard way of the error handling and is not an undefined behaviour.
If you throw in constructor it is assumed that an object was not initialized properly, so its destructor is not called.
53. What is a default constructor? Give an example
A default constructor is a constructor that either has no parameters, or if it has parameters, all the parameters have default values.
Default constructors do not take any parameters.
If a default constructor is not provided by the programmer explicitly, then the compiler provides a implicit default constructor.
In that case, the default values of the variables are 0.
Example:
class X
{
public:
X();
// Default constructor with no arguments
X(int = 0);
// Default constructor with one default argument
X(int, int , int = 0);
// Constructor
};
54. When are copy constructor called?
A Copy Constructor may be called in following cases:
1. When an object of the class is returned by value.
2. When an object of the class is passed (to a function) by value as an argument. 3. When an object is constructed based on another object of the same class.
55. Is it possible to access private data members of a class without using a member or a friend function?
Yes, it is possible using pointers. See the following program as an example.
#include<iostream>
using namespace std;
class Test
{
private:
int data;
public:
Test()
{
data = 0;
}
int getData()
{
return data;
}
};
int main()
{
Test t;
int* ptr = (int*)&t;
*ptr = 20;
cout << t.getData();
return 0;
}
56. what is the order of constructor and destructor call during inheritance in C++
* Base class constructor will always be called in the derived class.
* Whenever you create a derived class object, base class constructor will be called first. * For multiple inheritance, base class constructor will be called in the order of inheritance.
* Destructor will be called in reverse order.
Example:
#include <iostream>
using namespace std;
// first base class
class Base_Class_1
{
public:
// first base class’s Constructor
Base_Class_1()
{
cout << “Inside first base class” << endl;
}
};
// second base class
class Base_Class_2
{
public:
// second base class’s Constructor
Base_Class_2()
{
cout << “Inside second base class” << endl;
}
};
// child class inherits Parent1 and Parent2
class Child : public Base_Class_1, public Base_Class_2
{
public:
// child class’s Constructor Child()
{
cout << “Inside child class” << endl;
}
};
int main()
{
// creating object of class Child Child obj1;
return 0;
}
Output:
Inside first base class
Inside second base class
Inside child class
57. Can a destructor be pure virtual in C++?
Yes, destructor can be virtual in C++.
Once you declare a destructor as pure virtual, the you must provide a function body for the pure virtual destructor.
Example:
#include <iostream>
using namespace std;
class Base
{
public:
virtual ~Base()=0;
// Pure virtual destructor
};
Base::~Base()
{
cout << “Pure virtual destructor from base class is called”;
}
class Derived : public Base
{
public:
~Derived()
{
cout << “~Derived() is executed\n”;
}
};
int main()
{
Base *b = new Derived();
delete b;
return 0;
}
Output:
~Derived() is executed
Pure virtual destructor from base class is called
58. Guess the output of the program 1
#include<iostream>
using namespace std;
class Point
{
public:
Point()
{
cout << “Constructor called”;
}
};
int main()
{
Point p1, *p2;
return 0;
}
Output:
Constructor Called
Why?
Only one object p1 is constructed here. p2 is just a pointer variable, not an object
59. Guess the output of the program 2
#include<iostream>
using namespace std;
class myPoint
{
public:
myPoint()
{
cout << “Normal Constructor calledn”;
}
myPoint(const myPoint &t)
{
cout << “Copy constructor calledn”;
}
};
int main()
{
myPoint *t1, *t2;
t1 = new myPoint();
t2 = new myPoint(*t1);
myPoint t3 = *t1;
myPoint t4;
t4 = t3;
return 0;
}
Output:
Normal Constructor called
Copy Constructor called
Copy Constructor called
Normal Constructor called
60. Guess the output of the program 3
using namespace std;
class X
{
public:
int x;
};
int main()
{
X a = {20};
X b = a;
cout << a.x << ” ” << b.x; return 0;
}
Output:
20 20
Why?
If we don’t write our own copy constructor, then compiler creates a default copy constructor which assigns data members one object to other object.
61. Guess the output of the program 4
#include<iostream>
#include<stdlib.h>
using namespace std;
class Test
{
public:
Test()
{ cout << “Constructor called”;
}
};
int main()
{
Test *t = (Test *) malloc(sizeof(Test));
return 0;
}
Output
<EMPTY>
Why?
malloc() doesn’t call constructor. If replace malloc() with new, the constructor is called.
62. Guess the output of the program 5
#include <iostream>
using namespace std;
class Test
{
public:
Test()
{
cout << “Hello from Test() “;
}
}a;
int main()
{
cout << “Main Started “;
return 0;
}
Output:
Hello from Test() Main Started
Why?
There is global object ‘a’ which is constructed before the main functions starts. Hence the constructor for a is called first, then main()’ execution begins.
63. Guess the output of the program 6
#include<iostream>
using namespace std;
class Test
{
public:
Test();
};
Test::Test()
{
cout << ” Constructor Called. “;
}
void fun()
{
static Test t1;
}
int main()
{
cout << ” Before fun() called. “;
fun();
fun();
cout << ” After fun() called. “;
return 0;
}
Output:
Constructor Called.
Before fun() called.
After fun() called.
Why?
The object “t” is static in fun(), so constructor is called only once.
64. Copy constructor vs assignment operator in C++
Copy Constructor
- The copy constructor is an overloaded constructor.
- The copy constructor initializes the new object with an already existing object.
class_name(cont class_name &object_name)
{
//body of the constructor
}
- Both the target object and the initializing object shares the different memory locations.
- If you do not define any copy constructor in the program, C++ compiler implicitly provides one.
Assignment Operator
- The assignment operator is a bitwise operator.
- The assignment operator assigns the value of one object to another object both of which are already in existence.
class_name Ob1, Ob2;
Ob2=Ob1;
- Both the target object and the initializing object shares same allocated memory.
- If you do not overload the “=” operator, then a bitwise copy will be made.
65. What is conversion constructor in C++?
- A class has a constructor which can be called with a single argument, then this constructor becomes conversion constructor.
- Such a constructor allows automatic conversion to the class being constructed.
#include<iostream>
using namespace std;
class Test
{
private:
int a;
public:
Test(int i) {a = i;}
void show() { cout<<” a = “<<a<<endl; }
};
int main()
{
Test t(20);
t.show();
t = 30;
t.show();
return 0;
}
Output:
a = 20
a = 30
More example:
class MyClass
{
public:
int a, b;
MyClass( int i ) {}
MyClass( const char* n, int k = 0 ) {}
MyClass( MyClass& obj ) {}
}
int main()
{
MyClass M = 1 ;
// which is an alternative to
MyClass M = MyClass(1) ;
MyClass M = “super” ;
// which is an alternative to
MyClass M = MyClass(“super”, 0) ;
// or
MyClass M = MyClass(“super”) ;
}
66. Passing a vector to constructor in C++
When class member is a vector object, we can simply assign in constructor.
#include <iostream>
#include <vector>
using namespace std;
class MyClass
{
vector<int> vec;
public:
MyClass(vector<int> v)
{ vec = v;
}
void print()
{
for (int i = 0; i < vec.size(); i++)
cout << vec[i] << ” “;
}
};
int main()
{
vector<int> vec;
for (int i = 1; i <= 5; i++)
vec.push_back(i);
MyClass obj(vec);
obj.print();
return 0;
}
67. Can destructor be private?
Yes. It can be private.
But if you create an object it will throw an error.
Example:
#include <iostream>
using namespace std;
class Test
{
private:
~Test() {}
};
int main()
{
Test t;//error
}
But if you create an object by using new operator, then compiler will not throw an error. As it will be programmers responsibility to delete the dynamically allocated object.
#include <iostream>
using namespace std;
class Test
{
private:
~Test() {}
};
int main()
{
Test* t = new Test; // No Error
}
68. Would destructor will be called in below program?
#include <iostream>
#include <vector>
using namespace std;
class a
{
public :
~a()
{
cout << “destructor”;
}
};
int main()
{
vector <a*> *v1 = new vector<a*>;
return 0;
}
Ans: No
Why?
Deleting dynamically allocated objects is not compiler’s job. If user doesn’t call “delete ptr” explicitly, the destructor wouldn’t be called.
69. what is explicit constructor in C++
We knew about conversion constructor.
But in some cases we don’t want implicit conversion to take place.
Consider the example below:
Suppose, you have a class String:
class String
{
public:
String(int n);
// allocate n bytes to the String object
String(const char *p); // initializes object with char *p
};
Now, if you try:
- String mystring = ‘x’;
The character ‘x’ will be implicitly converted to int and then the String(int) constructor will be called. - But, this is not what the user might have intended. So, to prevent such conditions, we shall define the constructor as explicit:
class String
{
public:
explicit String (int n);//allocate n bytes
String(const char *p); // initialize sobject with string p
};
Virtual Functions Questions
70. What are pure virtual functions?
Pure virtual functions are also called as abstract classes in C++.
Below shows how to create a pure virtual function:
// Pure Virtual Function
virtual void myFunc() = 0;
A pure virtual function is implemented by classes which are derived from a Abstract class.
Complete example:
#include<iostream>
using namespace std;
class Base
{
public:
virtual void fun() = 0;
};
class Derived: public Base
{
public:
void fun()
{
cout << “fun() called”;
}
};
int main(void)
{
Derived d;
d.fun();
return 0;
}
Output:
fun() called
Important points to remember for pure virtual functions:
1. A class is abstract if it has at least one pure virtual function.
2. You cannot create an object for abstract class.
3. If we do not override the pure virtual function in derived class, then derived class also becomes abstract class.
4. An abstract class can have constructors.
71. What are vtables and how they are created?
- To implement virtual functions, C++ uses a special form of late binding known as the virtual table or vTable.
- The virtual table is a lookup table of functions used to resolve function calls in a dynamic/late binding manner.
- Every class that uses virtual functions (or is derived from a class that uses virtual functions) is given its own virtual table.
- This table is simply a static array that the compiler creates at compile time. A virtual table contains one entry for each virtual function that can be called by objects of the class.
- Each entry in this vTable is simply a Function Pointer that points to the most-derived function accessible by that class ie the most Base Class.
- The compiler also adds a hidden pointer to the base class, which we will call *__vPtr.
- __vPtr is set (automatically) when a class instance is created so that it points to the virtual table for that class. *__vPtr is inherited by derived classes
72. What are virtual functions?
Consider the example below:
#include<iostream>
using namespace std;
class base
{
public:
void print ()
{
cout<< “In base class” <<endl;
}
};
class derived:public base
{
public:
void print ()
{
cout<< “In derived class” <<endl;
}
};
int main()
{
base *bptr;
derived d;
bptr = &d;
bptr->print();
}
Output:
In base class
As you can see from the output, when we try to access derived class print function through base class pointer, base class print() will be called. This is not the expected result.
Why?
Because we have re-defined “print()” in the derived class, the compiler is binding the “print()” in compile time.
To make it as a runtime polymorphism, we need to declare the base class function as “virtual”, thus making the print() to work as a run time polymorphism.
Example:
#include<iostream>
using namespace std;
class base
{
public:
void print ()
{ cout<< “In base class” <<endl;
}
};
class derived:public base
{
public:
void print ()
{
cout<< “In derived class” <<endl;
}
};
int main()
{
base *bptr;
derived d;
bptr = &d;
bptr->print();
}
Output:
In derived class
Below are some rules for virtual polymorphism:
Virtual functions cannot be static and also cannot be a friend function of another class.
Virtual functions should be accessed using pointer or reference of base class type to achieve run time polymorphism.
The prototype of virtual functions should be same in base as well as derived class.
73. what will be the output of the below program – 1 ?
#include<iostream>
using namespace std;
class Base
{
public:
virtual void show()
{
cout<<” In Base \n”;
}
};
class Derived: public Base
{
public:
void show()
{
cout<<“In Derived \n”;
}
};
int main(void)
{
Base *bp = new Derived;
bp->show();
Base &br = *bp;
br.show();
return 0;
}
Output:
In Derived
In Derived
Why?
As show() is made as virtual, hence while calling, it is called according to the type of object being pointed, rather than the type of pointer or reference.
74. what will be the output of the below program – 2 ?
#include<iostream>
using namespace std;
class Base
{
public: virtual void show()
{
cout<<” In Base \n”;
}
};
class Derived: public Base
{
public:
void show()
{ cout<<“In Derived \n”;
}
};
int main(void)
{
Base *bp, b;
Derived d;
bp = &d;
bp->show();
bp = &b;
bp->show();
return 0;
}
Output:
In Derived
In Base
75. what will be the output of the below program – 3 ?
#include<iostream>
using namespace std;
class MyClass
{
public:
virtual void show() = 0;
};
int main(void)
{
MyClass b;
MyClass *bp;
return 0;
}
Output:
Error at “MyClass b;”.
Why?
Since MyClass has a pure virtual function, it becomes an abstract class and hence an instance of it cannot be created.
Hence there is an error in line “MyClass b”.
Note that there is no error in line “MyClass *bp;”. We can have pointers or references of abstract classes.
76. what will be the output of the below program – 4 ?
#include<iostream>
using namespace std;
class Base
{
public:
virtual void show() = 0;
};
class Derived : public Base { };
int main(void)
{
Derived d;
return 0;
}
Output:
Error at the line “Derived d;”
77. what will be the output of the below program – 5 ?
#include<iostream>
using namespace std;
class Base
{
public: Base()
{
cout<<“Constructor: Base”<<endl;
}
virtual ~Base()
{
cout<<“Destructor : Base”<<endl;
}
};
class Derived: public Base
{
public: Derived()
{
cout<<“Constructor: Derived”<<endl;
}
~Derived()
{
cout<<“Destructor : Derived”<<endl;
}
};
int main()
{
Base *base = new Derived();
delete base;
return 0;
}
Output:
Constructor: Base
Constructor: Derived
Destructor : Derived
Destructor : Base
Why?
As we have made destructor as virtual, derived class destructor will call base class destructor.
78. what will be the output of the below program – 6 ?
#include<iostream>
using namespace std;
class Base
{
public: virtual void show()
{
cout<<” In Base \n”;
}
};
class Derived: public Base
{
public: void show()
{
cout<<“In Derived \n”;
}
};
int main(void)
{
Base *bp = new Derived;
bp->Base::show();
return 0;
}
Output:
In Base
Why?
Note the line “bp->Base::show();”. We can use base class show(), by using scopr resolution operator. “::”
79. Can static functions be virtual in C++?
No, static functions cannot be virtual.
#include<iostream>
using namespace std;
class MyCLass
{
public: // Error: Virtual member functions cannot be static
virtual static void myFun()
{
}
};
static member function cannot be const and volatile.
#include<iostream>
using namespace std;
class MyCLass
{
public:
// Error: Static member function cannot be const
static void myFun() const
{
}
};
80. Is it possible to call a virtual function inside a non-virtual function in C++?
Consider the example below:
#include <iostream>
using namespace std;
class Base
{
public:
virtual void print()
{
cout << “Base class print function \n”;
}
void invoke()
{
cout << “Base class invoke function \n”; this -> print();
}
};
class Derived: public Base
{
public:
void print()
{
cout << “Derived class print function \n” ;
}
void invoke()
{
cout << “Derived class invoke function \n”;
this -> print(); // called under non – virtual function
}
};
int main()
{
Base *b = new Derived;
b -> invoke();
return 0;
}
Output:
Base class invoke function
Derived class print function
From the above output we can infer that polymorphic behaviour works even when a virtual function is called inside a non-virtual function.
81. what are virtual base class in C++ ?
When a derived class has multiple copies of base class, compiler will throw an error because derived class could have duplicate sets of members inherited from a single base class.
To resolve this error, we need to use virtual base class.
Program with error:
#include<iostream.h>
#include<conio.h>
class ClassA
{
public:
int a;
};
class ClassB : public ClassA
{
public:
int b;
};
class ClassC : public ClassA
{
public: int c;
};
class ClassD : public ClassB, public ClassC
{
public:
int d;
};
void main()
{
ClassD obj;
obj.a = 10; //Statement 1, Error occur
obj.b = 20;
obj.c = 30;
obj.d = 40;
cout<< “\n A : “<< obj.a;
cout<< “\n B : “<< obj.b;
cout<< “\n C : “<< obj.c;
cout<< “\n D : “<< obj.d;
}
ClassB & ClassC inherit ClassA, they both have single copy of ClassA. But ClassD inherit both ClassB & ClassC, hence ClassD have two copies of ClassA, one from ClassB and another from ClassC.
To resolve this, we use virtual base class as below:
#include<iostream.h>
#include<conio.h>
class ClassA
{
public:
int a;
};
class ClassB : virtual public ClassA
{
public:
int b;
};
class ClassC : virtual public ClassA
{
public:
int c;
};
class ClassD : public ClassB, public ClassC
{
public:
int d;
};
void main()
{
ClassD obj;
obj.a = 10;
obj.b = 20;
obj.c = 30;
obj.d = 40;
cout<< “\n A : “<< obj.a;
cout<< “\n B : “<< obj.b;
cout<< “\n C : “<< obj.c;
cout<< “\n D : “<< obj.d;
}
82. Explain few points on Virtual Table.
- All the classes that have a virtual function, or any class derived from the base class, will have its own virtual table.
- The table will be setup by compiler at compile time.
- Virtual table contains one entry as a function pointer for each virtual function that can be called by objects of the class.
83. Explain few points on _vptr
- vtable pointer or _vptr, is a hidden pointer added by the Compiler to the base class.
- This pointer is pointing to the virtual table of that particular class.
- _vptr is inherited to all the derived classes.
- Each object of a class with virtual functions stores this_vptr.
Object Oriented Programming Questions
84. What is diamond problem in C++ and how to solve it?
The diamond problem occurs when two super classes of a class have a common base class.
Consider below program:
class A
{
void display()
{
//some code
}
}
class B : public A
{
void display()
{
//some code
}
}
class C : public A
{
void display()
{
//some code
}
}
class D : public B, public C{
//contains two display() functions
}
If we call display() function using class D object then ambiguity occurs because compiler gets confused that whether it should call display() that came from class B or from class C.
How to Solve Diamond Problem in C++?
We can remove diamond problem by using virtual keyword.
class A
{
void display()
{
//some code
}
}
class B : virtual public A
{
void display()
{
//some code
}
}
class C : virtual public A
{
void display()
{
//some code
}
}
class D : public B, public C
{
//contains one display() functions
}
85. What is the difference between Local Variables, Instance Variables and Static Variables in C++
Local Variables :
- Variable defined within a block or method or constructor is called local variable.
- These variable are created when the block in entered or the function is called and destroyed after exiting from the block or when the call returns from the function.
- The scope of these variables exists only within the block in which the variable is declared.
Instance Variables :
- Instance variables are non-static variables and are declared in a class outside any method, constructor or block.
- As instance variables are declared in a class, these variables are created when an object of the class is created and destroyed when the object is destroyed.
- Instance Variable can be accessed only by creating objects.
Static Variables
- Static variables are also known as Class variables.
- Static variable can only have one copy of a static variable per class irrespective of how many objects we create.
- Initialization of Static Variable is not Mandatory. Its default value is 0
- To access static variables, we can simply access the variable as class_name::variable_name;
86. Can a static function access non-static member variables of class? Give reason.
- No, Static function of a class in C++ cannot access non-static variables.
- It can access static variable only.
- Static function is not associated with class object, means without object using class name only it can be called.
- whereas non-static variables are associated with objects.
- Every object has its own copy of non-static variable.
- Since, static function does not know about object, so, it is impossible for a static function to know on which class object or class instance it is being called.
87. Static function has “this” pointer?
- No static function will not have this pointer.
- Whenever we call a class non-static member function using class object then THIS pointer is also passed to the function as a parameter internally and this is why a non-static member function of a class know that on which class object it is being called in case of multiple objects creation of the class.
- Static function of a class is not associated with class object. So, THIS pointer is not passed to a static function as an internal parameter. So, a static function does not understand THIS pointer inside its body.
88. what is inheritance? List different types of it. Does C++ support Multilevel and Multiple Inheritances?
- Inheritance is a concept where a child class will acquire the properties [data members] and functionality [member functions] of a parent class.
- Child Class: A class that inherits another class is called as child class.
- Parent Class: The class that is being inherited is called as parent class.
Example:
#include <iostream>
using namespace std;
class Account
{
public:
float salary = 90000;
};
class Programmer: public Account
{
public:
float bonus = 40000;
};
int main(void)
{
Programmer p1;
cout<<“Salary: “<<p1.salary<<endl;
cout<<“Bonus: “<<p1.bonus<<endl;
return 0;
}
C++ supports five types of inheritance:
- Single inheritance
- Multiple inheritance
- Hierarchical inheritance
- Multilevel inheritance
- Hybrid inheritance
Yes, C supports both support Multilevel and Multiple Inheritances.
89. what is Single inheritance ? Explain with an example
A derived class is inherited from only one base class is called as single inheritance.
Example:
#include <iostream>
using namespace std;
class A
{
public:
A()
{
cout<<“Constructor of A class”<<endl;
}
};
class B: public A
{
public: B()
{
cout<<“Constructor of B class”;
}
};
int main()
{
//Creating object of class B
B obj;
return 0;
}
90.What is Multiple inheritance?
Explain with an example In this type of inheritance, a class can inherit more than one class. It means that in this type of inheritance a single child class can have multiple parent classes.
Example:
#include <iostream>
using namespace std;
class A
{
public:
A()
{
cout<<“Constructor of A class”<<endl;
}
};
class B
{
public:
B()
{
cout<<“Constructor of B class”<<endl;
}
};
class C: public A, public B
{
public:
C()
{
cout<<“Constructor of C class”<<endl;
}
};
int main()
{
C obj;
return 0;
}
Output:
Constructor of A class
Constructor of B class
Constructor of C class
91. What is Hierarchical inheritance? Explain with an example
In this type of inheritance, one parent class has more than one child class.
Example:
#include <iostream>
using namespace std;
class A
{
public:
A()
{
cout<<“Constructor of A class”<<endl;
}
};
class B: public A
{
public:
B()
{
cout<<“Constructor of B class”<<endl;
}
};
class C: public A
{
public:
C()
{
cout<<“Constructor of C class”<<endl;
}
};
int main()
{
C obj;
return 0;
}
Output:
Constructor of A class
Constructor of C class
92. What is Multilevel inheritance? Explain with an example
using namespace std;
class A
{
public:
A()
{
cout<<“Constructor of A class”<<endl;
}
};
class B: public A
{
public:
B()
{
cout<<“Constructor of B class”<<endl;
}
};
class C: public B
{
public:
C()
{
cout<<“Constructor of C class”<<endl;
}
};
int main()
{
//Creating object of class C
C obj;
return 0;
}
Output:
Constructor of A class
Constructor of B class
Constructor of C class
93. What is Hybrid inheritance? Explain with an example
Hybrid inheritance is a combination of more than one type of inheritance.
Example:
#include <iostream>
using namespace std;
class A
{
public:
A()
{
cout<<“Constructor of A class”<<endl;
}
};
class B : public A
{
public:
B()
{
cout<<“Constructor of B class”<<endl;
}
};
class C
{
public:
C()
{
cout<<“Constructor of C class”<<endl;
}
};
class D : public B, public C //D is derived from class B and class C
{
public:
D()
{
cout<<“Constructor of A class”<<endl;
}
};
int main()
{
D obj1;
//object of derived class D
return 0;
} //end of program
94. What is a namespace in C++? Explain with an example.
Namespace is used to prevent name conflicts.
Example:
namespace foo
{
class bar
{
//define it
};
}
namespace baz
{
class bar
{
// define it
};
}
As you can see above we have two classes name bar, that are completely different and separate thanks to the namespacing.
Symbols declared inside a namespace block are placed in a named scope that prevents them from being mistaken for identically-named symbols in other scopes.
95. Is it possible to create unnamed namespace?
Yes, it is possible to create unnamed namespace.
The name will be assigned by compiler.
The unnamed namespaces you have created will only be accessible within the file you created it in.
Example:
#include <iostream>
using namespace std;
// unnamed namespace declaration
namespace
{
int num = 30;
}
int main()
{
cout << num << “\n”;
return 0;
}
96. What is a class in C++
- Class is a user defined data type
- To use a class you need to create an object
- Class can be considered as a blueprint. You can see what a class contains, but you cannot use it until you create an object.
Example of a class:
class myClass
{
public:
int data_memeber_1;
double data_memeber_2;
void member_function()
{
// code to drive the car
}
};
97. What are abstract class?
A class that cannot be instantiated and is usually implemented as a class that has one or more pure virtual (abstract) functions.
class AbstractClass
{
public:
virtual void AbstractMemberFunction() = 0; // Pure virtual function makes this class Abstract class.
virtual void NonAbstractMemberFunction1(); // Virtual function.
void NonAbstractMemberFunction2();
};
98. What is an object in C++
An object is created from a class.
An object is an instance of a class.
class MyClass
{
public:
int myNum; // Attribute (int variable)
};
int main()
{
MyClass myObj; // object of MyClass
myObj.myNum = 15;
cout << myObj.myNum << “\n”;
return 0;
}
99. What is polymorphism? What are it’s different forms explain with code.
- Polymorphism means many forms.
- In C++ context, polymorphism means single function with same name, behave differently in different contexts.
For example, the + (plus) operator in C++:
4 + 5 <– integer addition
3.14 + 2.0 <– floating point addition
s1 + “bar” <– string concatenation!
There are 2 types of Polymorphism.
1. Compile Time Polymorphism:
This is also known as static (or early) binding.
- Function Overloading
- Operator Overloading
Function Overloading Example:
#include <iostream>
using namespace std;
class Add
{
public:
int sum(int num1, int num2)
{
return num1+num2;
}
int sum(int num1, int num2, int num3)
{
return num1+num2+num3;
}
};
int main()
{
Add obj;
//This will call the first function
cout<<“Output: “<<obj.sum(10, 20)<<endl;
//This will call the second function
cout<<“Output: “<<obj.sum(11, 22, 33);
return 0;
}
2. Run time polymorphism:
This is also known as dynamic (or late) binding. Virtual Functions
#include <bits/stdc++.h>
using namespace std;
class super
{
public:
virtual void print ()
{
cout<< “print super class” <<endl;
}
void show ()
{
cout<< “show super class” <<endl;
}
};
class derived:public super
{
public:
void print ()
{
cout<< “print derived class” <<endl;
}
void show ()
{
cout<< “show derived class” <<endl;
}
}; /
/main function
int main()
{
super *sPtr;
derived d;
sPtr = &d;
//virtual function, binded at runtime (Runtime polymorphism)
sPtr->print();
// Non-virtual function, binded at compile time
sPtr->show();
return 0;
}
100. Example for -> Operator with structure
struct Point
{
int x;
int y;
};
Point* p; // declare pointer to a Point struct
p = new Point; // dynamically allocate a Point
p->x = 12; // set the field values.
p->y = 34;
101. What is encapsulation, explain with an example
Encapsulation is a process of combining data members and functions in a single unit called class.
This is to prevent the access to the data directly, the access to them is provided through the functions of the class.
How Encapsulation is achieved in a class
To do this:
1) Make all the data members private.
2) Create public setter and getter functions for each data member in such a way that the set function set the value of data member and get function get the value of data member.
#include<iostream>
using namespace std;
class ExampleEncap
{
private:
int num;
char ch;
public:
int getNum()const
{
return num;
}
char getCh() const
{
return ch;
}
void setNum(int num)
{
this->num = num;
}
void setCh(char ch)
{
this->ch = ch;
}
};
int main()
{
ExampleEncap obj;
obj.setNum(100);
obj.setCh(‘A’);
cout<<obj.getNum()<<endl;
cout<<obj.getCh()<<endl;
return 0;
}
102. What is Data Abstraction, explain with an example.
Data Abstraction is a process of providing only the essential details to the outside world and hiding the internal details .
Data Abstraction is a programming technique that depends on the separation of the interface and implementation details of the program.
Abstraction using Classes: We can implement Abstraction in C++ using classes. Class helps us to group data members and member functions using available access specifiers.
Abstraction in Header files: One more type of abstraction in C++ can be header files. For example, consider the pow() method present in math.h header file
103. What are different types of storage classes, explain each of the storage classes in c++
There are 5 storage classes available in C++
- auto
- register
- static
- extern
- mutable
auto Storage Class:
The auto storage class is the default storage class for all local variables.
{
int mount;
auto int month;
}
register Storage Class:
The register storage class is used to define local variables that should be stored in a register instead of RAM.
{
register int miles;
}
static Storage Class:
The static storage class instructs the compiler to keep a local variable in existence during the life-time of the program instead of creating and destroying it each time it comes into and goes out of scope.
static int count = 10; /* Global variable */
extern Storage Class:
The extern storage class is used to give a reference of a global variable that is visible to ALL the program files.
extern int count;
mutable Storage Class:
mutable storage class is applicable to only class data members.
If a data member of a class is declared as mutable, then it can be modified by an object which is declared as constant.
104. What are different types of access specifiers available in C++
Below are different access specifiers available in C++
Public: Data members and functions are accessible outside the class.
Private: Data members and functions cannot be accessed outside the class. The exception is the usage of a friend class.
Protected: Data members and functions are accessible only to the derived classes.
105. What is a scope resolution operator?
In C++, scope resolution operator is :: is used for following purposes.
- To access a global variable when there is a local variable with same name:
- To define a function outside a class.
- To access a class’s static variables. In case of multiple Inheritance, if same variable name exists in two ancestor classes, we can use scope resolution operator to distinguish.
- For namespace
- Refer to a class inside another class:
Example: outside::inside B;
106. Example for Nested Classes in C++
A class which is declared in another enclosing class is called as Nested Classes.
Example:
#include<iostream>
using namespace std;
class OuterClass
{
private:
int x;
class NestedClass
{
int y;
void NestedFun(Enclosing *e)
{
cout<<e->x;
}
};
};
int main()
{
}
107. Explain IS-A and HAS-A relationship in inheritance
“IS A” : Establishes relation between related objects. You can use inheritance to establish the relation.
“HAS A”: Defines a capability for possibly unrelated objects. You can use interface to define the capability.
Example:
A car is-a vehicle
A car has-a steering wheel
108. Difference between C++ Struct and C++ class
In structure have a by default public. In class have a by default private.
Structure cannot be inherited. But class can be inherit.
There is no data hiding features comes with structures. Classes do, private, protected and public.
A structure can’t be abstract, a class can.
A structure is a value type, while a class is a reference type.
A structure is contain only data member , but class contain data member and member function.
In a Structure we can’t initialise the value to the variable but in class variable we assign the values.
Structure are value type, They are stored as a stack on memory. whereas class are reference type. They are stored as heap on memory.
109. what is meant by Dynamic Constructor in C++
Allocation of memory is done dynamically using dynamic memory allocator new in a constructor, it is known as dynamic constructor.
#include <iostream>
using namespace std;
class MyClass
{
const char* p;
public:
// default constructor
MyClass()
{
// allocating memory at run time
p = new char[6];
p = “hello”;
}
void display()
{
cout << p << endl;
}
};
int main()
{
MyClass obj = new MyClass();
obj.display();
}
110. How to access static member of a class? Give example
By using scope resolution operator.
#include <iostream>
using namespace std;
class A
{
public:
static int x;
static int getX() {return x;} // static member function
};
int A::x; // static member variable
int main()
{
A::x = 100;
cout<<A::getX();
return 0;
}
111. List few points about static member variable
• Belongs to the whole class, and there is only one of it, regardless of the number of objects.
• Must be defined and initialized outside of any function, like a global variable.
• It can be accessed by any member function of the class.
• Normally, it is accessed with the class scope operator. If it is private, use a static member function to read or write it.
112. List few points about static member function.
• Is like an ordinary non-member function, but its scope is the class.
• It can access all members of an object in its class, but only if you make the object available, such as in a parameter – there is no “this” object.
• Normally, it is called with the class scope operator.
113. How to do Constructor Delegation in C++
Sometimes it is useful for a constructor to be able to call another constructor of the same class.
This feature, called Constructor Delegation, was introduced in C++ 11.
Consider below class:
class A
{
int x, y, z;
public:
A()
{
x = 0;
y = 0;
z = 0;
}
A(int z)
{
// The below two lines are redundant
x = 0;
y = 0;
this->z = z;
}
};
Hence C++, allows us to eliminate redundant code with the help of constructor delegation, by allowing to call a constructor by placing it in the initializer list of other constructors.
class A
{
int x, y, z;
public:
A()
{
x = 0;
y = 0;
z = 0;
}
// Constructor delegation
A(int z) : A()
{
this->z = z; // Only update z
}
};
114. what is the reason that we should write our own copy constructor?
If we don’t provide any implementation of copy constructor C++ compiler provide default copy constructor.
The problem with default copy constructor is that When we have members which dynamically gets initialized at run time, default copy constructor copies this members with address of dynamically allocated memory and not real copy of this memory.
Now both the objects points to the same memory and changes in one reflects in another object.
Hence, in such cases, we should always write our own copy constructor
115. How to prevent Object Copy in C++ ?
Keeping the Copy Constructor and Copy assignment operator as private in the class
#include <iostream>
using namespace std;
class Base {
int x;
public:
Base() { }
Base(int y): x(y) { }
private:
// Copy constructor
Base(const Base& obj) : x(obj.x) { }
// copy assignment operator
Base& operator=(const Base& tmp_obj)
{
x = tmp_obj.x;
return *this;
}
};
int main()
{ Base b1(10);
Base b2(b1); // error: calls copy constructor
b2 = b1; // error: calls copy assignment operator
return 0;
}
116. Is it possible to create nested namespace in C++?
Yes it is possible to create nested namespace.
Example:
namespace X
{
void foo()
{
cout << “foo from X is called” << endl;
}
namespace Y
{
void foo()
{ cout << “foo from Y is called” << endl;
}
}
}
Calling:
X::Y::foo();
117. Is it possible to create an alias for namespace?
Yes it is possible to create.
Syntax:
Namespace newName = oldName .
namespace newName = old_name;
newName::myFunc()
118. List down all the concepts of OOP.
Below are the concepts that are available in OOP
- Classes.
- Objects.
- Encapsulation.
- Polymorphism.
- Inheritance.
- Abstraction.
- Overloading.
- Error handling.
Classes: They are user defined data type.
Objects: They are instance of a class.
Encapsulation: Data members and member functions are encapsulated to restrict the access some of the object’s data from outside of class.
Polymorphism: It is a concept where a member function with same name will behave differently on different situations.
Inheritance: This concept is used to inherit some properties from base class to derived class.
Abstraction: In this concept consists in hiding the details of processing and representing only necessary information and result outside the class.
Error handling: In this concept, we handle the errors that can appear run time.
119. Example for Abstraction in C++
Abstraction is a concept where we show only relevant details and hide the complex details from the user.
Below is the example for abstraction:
Usually in OOP abstraction is achieved for data members, by making them private and modifying them with the help of getters and setters.
#include <iostream>
using namespace std;
class AbstractionExample
{
private:
int num;
public:
void setNum(int n)
{
num = n;
}
void getNum()
{
cout<<“Numbers is: “<<num<< endl;
}
};
int main()
{
AbstractionExample obj;
obj.setMyValues(100);
obj.getMyValues();
return 0;
}
120. Explain upcasting and downcasting in C++
Upcasting: Converting the derived class pointer to the base class pointer or converting the derived class reference to the base class reference is called as upcasting.
There are two ways are creating upcasting relationship:
Method 1:
Parent* parentObj; // Parent class pointer
Child childObj; // Creating child class object
parentObj = &childObj; // assigning to address reference of base class object
Method 2:
Parent &parentObj; // Parent class reference
Child childObj; // Creating child class object
parentObj = childObj; // direct assignment
Downcasting
In this process converting a base-class pointer or reference to a derived-class pointer or reference.
We cannot do this implicitly thus, we have to define explicitly.
Child *child = (Child) &parent;
121. what is difference between public, private and protected members?
Public Members:
The data members declared under public will be available to everyone.
The data members and member functions declared public can be accessed from other classes too.
Private Members:
The data members declared as private can be accessed only by the functions inside the class.
Only the member functions or the friend functions are allowed to access the private data members of a class.
Protected Members:
Protected access modifier is similar to that of private access modifiers.
The class member declared as Protected are inaccessible outside the class but they can be accessed by any subclass(derived class) of that class.
122. what is object slicing in C++?
Object slicing happens when a derived class object is assigned to a base class object, additional attributes of a derived class object are sliced off to form the base class object.
class A
{
int foo;
};
class B : public A
{
int bar;
};
So an object of type B has two data members, foo and bar.
Then if you were to write this:
B b;
A a = b;
Then the information in b about member bar is lost in a.
123. Guess the output of Inheritance Program 1
#include<iostream>
using namespace std;
class Base1
{
public:
Base1()
{
cout << ” Base1’s constructor called” << endl;
}
};
class Base2
{
public: Base2()
{
cout << “Base2’s constructor called” << endl;
}
};
class Derived: public Base1, public Base2
{
public: Derived()
{
cout << “Derived’s constructor called” << endl;
}
};
int main()
{
Derived d;
return 0;
}
Output:
Base1′s constructor called
Base2′s constructor called
Derived’s constructor called
Why?
Constructors of base classes are called in the same order as they are specified in inheritance.
124.Guess the output of Inheritance Program 2
#include <iostream>
using namespace std;
class Base1
{
public:
~Base1() { cout << ” Base1’s destructor” << endl;
}
};
class Base2 {
public:
~Base2() { cout << ” Base2’s destructor” << endl;
}
};
class Derived: public Base1, public Base2 {
public:
~Derived() { cout << ” Derived’s destructor” << endl;
}
};
int main()
{
Derived d;
return 0;
}
Output:
Derived’s destructor
Base2’s destructor
Base1’s destructor
Why?
Destructors are always called in reverse order of constructors.
125. Guess the output of Inheritance Program 3
#include<iostream>
using namespace std;
class base
{
int arr[10];
};
class b1: public base { };
class b2: public base { };
class derived: public b1, public b2 {};
int main(void)
{
cout << sizeof(derived);
return 0;
}
Output:
80
Why?
Both b1 and b2 inherit base class, 2 copies of base class will be there in derived class. This situation can be resolved by virtual classes.
126. Guess the output of Inheritance Program 4
#include<iostream>
using namespace std;
class Base {};
class Derived: public Base {};
int main()
{
Base *bp = new Derived;
Derived *dp = new Base;
}
Output:
Error in ” Derived *dp = new Base;”
Why?
A Base class pointer/reference can point/refer to a derived class object, but the other way is not possible
127. Guess the output of Inheritance Program 5
#include<iostream>
using namespace std;
class Base1
{
public:
char c;
};
class Base2
{
public:
int c;
};
class Derived: public