Here is a listing of advanced C++ interview questions on “Derivation and Templates” along with answers, explanations and/or solutions:
1. Which is dependant on template parameter?
a) base class
b) abstract class
c) method
d) static class
Answer: a
Clarification: Base class is dependant on template parameter.
2. Which value is placed in the base class?
a) derived values
b) default type values
c) both default type & derived values
d) null value
Answer: b
Clarification: We can place the default type values in a base class and overriding some of them through derivation.
3. How many bits of memory needed for internal representation of class?
a) 1
b) 2
c) 4
d) no memory needed
Answer: d
Clarification: classes that contain only type members, nonvirtual function members, and static data members do not require memory at run time.
4. What will be the output of the following C++ code?
-
#include -
using namespace std;
-
class class0 -
{ -
public:
-
virtual ~class0(){}
-
protected:
-
char p;
-
public:
-
char getChar();
-
};
-
class class1 : public class0
-
{ -
public:
-
void printChar();
-
};
-
void class1::printChar()
-
{ -
cout << "True" << endl;
-
} -
int main()
-
{ -
class1 c; -
c.printChar();
-
return 1;
-
}
a) True
b) error
c) no output
d) runtime error
Answer: a
Clarification: In this program, We are passing the values and inheriting it to the other class and printing the result.
$ g++ dert.cpp $ a.out True
5. What will be the output of the following C++ code?
-
#include -
using namespace std;
-
template<typename T>class clsTemplate
-
{ -
public:
-
T value; -
clsTemplate(T i)
-
{ -
this->value = i;
-
} -
void test()
-
{ -
cout << value << endl;
-
} -
};
-
class clsChild : public clsTemplate<char>
-
{ -
public:
-
clsChild(): clsTemplate<char>( 0 )
-
{ -
} -
clsChild(char c): clsTemplate<char>( c )
-
{ -
} -
void test2()
-
{ -
test();
-
} -
};
-
int main()
-
{ -
clsTemplate <int> a( 42 );
-
clsChild b( 'A' );
-
a.test();
-
b.test();
-
return 0;
-
}
a) 42
b) A
c)
42 A
d)
A 42
View Answer
Clarification: In this program, We are passing the values by using the template inheritance and printing it.
Output:
$ g++ dert.cpp $ a.out 42 A
6. What will be the output of the following C++ code?
-
#include -
using namespace std;
-
template <class T>
-
class A -
{ -
public:
-
A(int a): x(a) {}
-
protected:
-
int x;
-
};
-
template <class T>
-
class B: public A<char>
-
{ -
public:
-
B(): A<char>::A(100)
-
{ -
cout << x * 2 << endl;
-
} -
};
-
int main()
-
{ -
B<char> test;
-
return 0;
-
}
a) 100
b) 200
c) error
d) runtime error
Answer: b
Clarification: In this program, We are passing the values and manipulating it by using the template inheritance.
Output:
$ g++ dert2.cpp $ a.out 200
