C++ExamplesQuizLiangCi
What gets printed? #include <iostream> struct Car { Car() : price(20000) {} Car(double b) : price(b*1.1) {} double price; }; struct Toyota : public virtual Car { Toyota(double b) : Car(b) {} }; struct Prius : public Toyota { Prius(double b) : Toyota(b) {} }; int main(int argc, char** argv) { Prius p(30000); std::cout << p.price << std::endl; return 0; } 20000 22000 30000 33000 code is ill-formed
description: 20000 is output. All sub-objects representing virtual base classes are initialized by the constructor of the most derived class. If the constructor of the most derived class does not specify a mem-initializer for a virtual base class V, then V's default construtor is called to initialize the virtual base class subobject.
How many times is Hello World printed by this program? #include <iostream> struct BS { BS() { std::cout << "Hello World" << std::endl; } unsigned int color; }; struct mid1 : virtual public BS { }; struct mid2 : virtual public BS { }; struct mid3 : public BS { }; struct mid4 : public BS { }; struct DR : public mid1, public mid2, public mid3, public mid4 { }; int main(int argc, char** argv) { DR d; return 0; } 1 2 3 code is ill-formed undefined
description: 3 times. One time for the first virtual occurences of BS in the heirarchy and once for each non-virtual occurence of BS. mid1 and mid2 together have one. mid3 and mid4 each have one.
What gets printed by this program? #include <iostream> struct Shape { virtual void print() { std::cout << "SHAPE" << std::endl; } virtual ~Shape() {} }; struct Box : private Shape { virtual void print() { std::cout << "BOX" << std::endl; } }; int main(int argc, char** argv) { Shape* s = new Box; s->print(); delete s; return 0; } SHAPE BOX undefined code is ill-formed unspecified
description: An implicit conversion from a pointer to a derived class, to a pointer to an inaccessible (private inheritance) base class is ill-formed. Thus the assignment of the new Box to Shape* is ill-formed.
Which of the following implementations of the reset function is best for initializing the array to all zero. class foo{ public: foo(){ reset(); } private: void reset(){ // A // memset(x, 0, 50); // B // memset(x, 0, sizeof(x)); // C // memset(x, 0, 50 * 4); // D // memset(x, 0, 50 * sizeof(x)); } long x[50]; }; A B C D none of them will work
description: B is the only answer that is portable. C will work on platforms where long is 4 bytes, but many platforms have 8 byte long.
Which of the following operators cannot be overloaded A . (Member Access or Dot operator) B ?: (Ternary or Conditional Operator ) C :: (Scope Resolution Operator) D .* (Pointer-to-member Operator ) E All of the above
E All of the above
When a copy constructor may be called? A-When an object of the class is returned by value. B-When an object of the class is passed (to a function) by value as an argument. C- When an object is constructed based on another object of the same class D-When compiler generates a temporary object. E- All of the above
E-All of the above
Lvalues and Rvalues
Every C++ expression is either an lvalue or an rvalue. An lvalue refers to an object that persists beyond a single expression. You can think of an lvalue as an object that has a name. All variables, including nonmodifiable (const) variables, are lvalues. An rvalue is a temporary value that does not persist beyond the expression that uses it.
#include <iostream> using namespace std; class A { public: virtual void fun() { cout << "A::fun() "; } }; class B: public A { public: void fun() { cout << "B::fun() "; } }; class C: public B { public: void fun() { cout << "C::fun() "; } }; int main() { B *bp = new C; bp->fun(); return 0; } A-A::fun() B-B::fun() C-C::fun()
-C::fun() Explanation: The important thing to note here is B::fun() is virtual even if we have not uses virtual keyword with it. When a class has a virtual function, functions with same signature in all descendant classes automatically become virtual. We don't need to use virtual keyword in declaration of fun() in B and C. They are anyways virtual. Question 14
Evaluate !(1 && !(0 || 1)) A. Unevaluatable B. False C. True
.C.True
What gets printed? 01 #include <iostream> 02 03 int main() 04 { 05 for (int i = 0; i < 4; ++i) 06 { 07 switch (i) 08 { 09 case 0 : std::cout << "0"; 10 case 1 : std::cout << "1"; continue; 11 case 2 : std::cout << "2"; break; 12 default : std::cout << "D"; break; 13 } 14 std::cout << "."; 15 } 16 return 0; 17 } 0.1.2. 01.2.D. 011.2.D 0112.D. Compiler error on line 10
0.112.D. description: Based on sections 6.4.2 p6 and 6.6.1 p1 of the standard, The first case label to match the given switch condition is executed,furthermore all subsequent cases (including the default case) will be executed until a break, continue, return or end of switch is encountered. In this case the continue not only exits from the switch but goes directly to the next iteration of the loop.
According to the C++11 standard, what is the output of this program? #include <iostream> int main() { for (int i = 0; i < 3; i++) std::cout << i; for (int i = 0; i < 3; ++i) std::cout << i; }
012012 Whether you post-increment or pre-increment i, its value does not change until after the loop body has executed.
What value gets printed by the program? #include <iostream> int main(int argc, char** argv) { int x; x = 1, 2, 3; std::cout << x << std::endl; return 0; } a- 1 b- 2 c- 3 d- 6 3- undefined
1- correct description: The operands to the comma operator are evaluated from left to right. The value of the left hand expression is discarded. The type and value of the result are the type type and value of the right hand operand. Note: assignment takes precedence over the comma operator, so in this case x=1 is evaluated first; than x, 2, 3
Which of the following is not the member of class? 1. Friend function 2. Virtual function 3. Static function 4. Const function
1.
Which of the following is not a type of constructor? 1. Friend constructor 2. Copy constructor 3. Default constructor 4. Parameterized constructor
1. Friend Constructor
Which of the following cannot be friend? 1. Object 2. Operator function 3. Class 4. Function
1.Object
What is the output of the program? #include <iostream> struct A { virtual int foo(int x = 5) { return x * 2; } }; struct B : public A { int foo(int x = 10) { return x * 3; } }; int main(int argc, char** argv) { A* a = new B; std::cout << a->foo() << std::endl; return 0; } a- 10 b- 15 c- 20 d- 30 e- ill-formed
15 - correct description: The method B::foo is called but with the default argument of 5 from A::foo. "A virtual function call uses the default arguments in the declaration of the virtual function determined by the static type of the pointer or reference denoting the object. An overriding function in a derived class does not acquire default arguments from the function it overrides."
Which of the following correctly describes overloading of functions? 1. Virtual polymorphism 2. Ad-hoc polymorphism 3. Pseudo polymorphism 4. Transient polymorphism
2. Ad-Hoc polymorphism
Which of the following concepts means adding new components to a program as it runs? 1. Dynamic typing 2. Dynamic loading 3. Dynamic binding 4. Data hiding
2.Dynamic Loading
According to the C++ standard which of the following declarations for the "main" function are valid? 1 int main(int argc, char** argv) 2 int main(char** argv, int argc) 3 int main() 4 inline int main(int argc, char* argv[]) 5 int main(char* argv[], int argc) 6 void main() 7 int main(int argc, char* argv[]) 8 static int main() 9 int main(int argc, char* argv[], char* options[]) 1, 6, 9 3, 4, 5, 7 1, 4, 8 3, 7, 9 - correct 3, 6
3, 7, 9 - correct description: According to section 3.6.1 pg2, main must return an int, and must have either no parameters or (int argc ,char* argv[]) as its first set of parameters. And in section 3.6.1 pg3: A program that declares main to be inline or static is ill-formed.
Which of the following statement is correct? 1. A constructor is called at the time of use of an object. 2. A constructor is called at the time of declaration of a class. 3. A constructor is called at the time of declaration of an object 4. A constructor is called at the time of use of a class.
3.
Which of the following concept of oops allows compiler to insert arguments in a function call if it is not specified? 1. Call by reference 2. Call by pointer 3. Default arguments 4. Call by value
3. Default arguments
Which of the following statements is correct? 1. Pointer to base class cannot be created. 2. Pointer to derived class cannot be created. 3. Derived class pointer cannot point to base class. 4. Base class pointer cannot point to derived class.
3. Derived class pointer cannot point to base class.
Which of the following concepts provides facility of using object of one class inside another class? 1. Encapsulation 2. Abstraction 3. Composition 4. Inheritance
3.Composition
Which of the following term is used for a function defined inside a class? 1. Classic function 2. Member Variable 3. Member function 4. Class function
3.Member function
What gets printed? #include <iostream> int foo(int i) { return 2; } double foo(double d) { return 4.0; } struct Computer { int foo(int i) { return 8; } }; struct Gateway : public Computer { double foo(double d) { return 16.0; } }; int main(int argc, char** argv) { Gateway g; std::cout << foo(1) + foo(1.0) + g.foo(1) + g.foo(1.0) << std::endl; return 0; } 20 30 38 40 The code is ill-formed
38- correct description: When calling global foo, the function is overloaded and each foo is called once depending on the type of the argument. When calling the member foo, Gateway::foo hides Computer::foo so Gateway::foo is called twice.
What value gets printed by the program? #include <iostream> int foo(int y); int foo(int x) { return x+1; } int main(int argc, char** argv) { int x = 3; int y = 6; std::cout << foo(x) << std::endl; return 0; } a- 3 b- 4 c- 9 d- ill-formed e- undefined
4 - correct The trick here is, we change the parameter names from the function declaration to function definition. This is legal, and only the parameter names in the function definition are used.
#include <iostream> using namespace std; class foo{ public: foo() : z(x+1), y(2), x(3) { cout << "z: " << z << endl; } private: int x; int y; int z; }; int main(int argc, char** argv){ foo f; return 0; } 1 2 3 4 undefined
4 - correct description: the value of z is initialized to 4. According the C++ standard: non-static data members shall be initialized in the order they were declared in the class definition, regardless of the order of the mem-initializers. Therefore x is initialized to 3 before z is initialized to X + 1.
How many times is Hello World printed by this program? #include <iostream> struct BS { BS() { std::cout << "Hello World" << std::endl; } }; struct mid1 : public BS { }; struct mid2 : public BS { }; struct mid3 : public BS { }; struct mid4 : public BS { }; struct DR : public virtual mid1, public virtual mid2, public virtual mid3, public mid4 { }; int main(int argc, char** argv) { DR d; return 0; } 0 3 4 undefined code is ill-formed
4 times. Virtual inheritance affects the class that is inherited virtually. Therefore the BS base class is not inherited virtually and there are 4 of them within 1 DR object. The virtual inheritance statements in this code are affecting the classes mid1, mid2, mid3, mid4 and not BS.
Why reference is not same as a pointer? 1. A reference can never be null. 2. Reference doesn't need an explicit dereferencing mechanism. 3. A reference once established cannot be changed. 4. All of the above.
4. All of above
Which of the following concepts means determining at runtime what method to invoke? 1. Dynamic Typing 2. Dynamic loading 3. Data hiding 4. Dynamic binding
4.Dynamic Binding
cout is a/an __________ . 1. operator 2. macro 3. function 4. object
4.Object
Which of the following type of class allows only one object of it to be created? 1. Friend class 2. Abstract class 3. Virtual class 4. Singleton class
4.Singleton
Which of the following is an abstract data type 1. string 2. int 3. double 4. Class
4.class
What gets printed for the value of z? #include <iostream> struct Foo { Foo(int n) : x(n++), y(n++), z(n++) {} int x; int y; int z; }; int main(int argc, char** argv) { Foo f(3); std::cout << "x: " << f.x << std::endl; std::cout << "y: " << f.y << std::endl; std::cout << "z: " << f.z << std::endl; return 0; } 3 4 5 code is ill-formed undefined
5- correct description: There is a sequence point after the initalization of each base and member, thus the code is well-formed and defined
What is the output of the program? #include <iostream> class Foo { public: char c; static double sd; double d; int i; }; int main(int argc, char** argv) { Foo f = { 72, 3.14 }; std::cout << f.c + f.d + f.i << std::endl; return 0; } a- 72 b- 75.14 c- ill-formed d- undefined
75.14 - correct description: "An aggregate is an array or a class with no user-declared constructors, no private or protected non-static data members, no base classes, and no virtual functions." Aggregates can be initialized by "brace-enclosed, comma separated list of initializer-clauses for the members of the aggregate, written in increasing subscript or member order." Static data members are skipped during this type of initialization so 3.14 initializes d and not sd in this example "If there are fewer initializers in the list than there are members in the aggregate, then each member not explicitly initialized shall be value-initialized". So in this example i is value-initialized to 0.
Which lines below should not compile? 1 struct A 2 { 3 A(int x) : n(x) {} 4 int n; 5 }; 6 7 int main(int argc, char** argv) 8 { 9 A a1; 10 A a2(2); 11 A a3(a2); 12 return 0; 13 } none 9 10 11 9 and 10 and 11
9 - correct description: If any user-declared constructor is present in the class, then no default constructor will be created implicitly. Additionally if no user declared copy constructor is declared, then an implicit copy constructor will be created by the compiler. In this example there is a user-declared constructor which prevents the default constructor from existing, but a copy constructor is still created implicitly.
Which of the following operators does NOT indicate a sequence point in the code? a- && b- || c- ? d- = e- ,
= -correct description: All of them except the assignment operator indicate a sequence point.
Which of the following are true about classes and struct? 1.A class is a reference type, whereas a struct is a value type. 2.Objects are created using new, whereas structure variables can be created either using new or without using new. 3.A structure variable will always be created slower than an object. 4.A structure variable will die when it goes out of scope. 5.An object will die when it goes out of scope. A) 1, 2, 4 B) 3, 5 C) 2, 4 D) 3, 4, 5
A
Output of following program? Assume that the size of int is 4 bytes and size of double is 8 bytes, and there is no alignment done by the compiler. #include<iostream> #include<stdlib.h> using namespace std; template<class T, class U, class V=double> class A { T x; U y; V z; static int count; }; int main() { A<int, int> a; A<double, double> b; cout << sizeof(a) << endl; cout << sizeof(b) << endl; return 0; } A 16 24 B 8 16 C 20 28 D Compiler Error: template parameters cannot have default values.
A 16 24 templates can also have default parameters. The rule is same all default values must be on the rightmost side. Since count is static, it is not counted in sizeof.
#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 *Var = new Derived(); delete Var; return 0; } A Constructor: Base Constructor: Derived Destructor : Derived Destructor : Base B Constructor: Base Constructor: Derived Destructor : Base C Constructor: Base Constructor: Derived Destructor : Derived D Constructor: Derived Destructor : Derived
A Since the destructor is vitrual, the derived class destructor is called which in turn calls base class destructor.
#include <iostream> using namespace std; class A { int id; static int count; public: A() { count++; id = count; cout << "constructor for id " << id << endl; } ~A() { cout << "destructor for id " << id << endl; } }; int A::count = 0; int main() { A a[3]; return 0; } A constructor for id 1 constructor for id 2 constructor for id 3 destructor for id 3 destructor for id 2 destructor for id 1 B constructor for id 1 constructor for id 2 constructor for id 3 destructor for id 1 destructor for id 2 destructor for id 3 C Compiler Dependent. D constructor for id 1 destructor for id 1
A constructor for id 1 constructor for id 2 constructor for id 3 destructor for id 3 destructor for id 2 destructor for id 1 In the above program, id is a static variable and it is incremented with every object creation. Object a[0] is created first, but the object a[2] is destroyed first. Objects are always destroyed in reverse order of their creation. The reason for reverse order is, an object created later may use the previously created object. For example, consider the following code snippet. A a; B b(a); In the above code, the object 'b' (which is created after 'a'), may use some members of 'a' internally. So destruction of 'a' before 'b' may create problems. Therefore, object 'b' must be destroyed before 'a'.
#include <iostream> using namespace std; int main() { try { throw 'a'; } catch (int param) { cout << "int exception\n"; } catch (...) { cout << "default exception\n"; } cout << "After Exception"; return 0; } A default exception After Exception B int exception After Exception C int exception D default exception
A default exception After Exception The block catch(...) is used for catch all, when a data type of a thrown exception doesn't match with any other catch block, the code inside catch(...) is executed. Note that the implicit type conversion doesn't happen when exceptions are caught. The character 'a' is not automatically converted to int.
Predict the output? #include <iostream> using namespace std; template <typename T> void fun(const T&x) { static int count = 0; cout << "x = " << x << " count = " << count << endl; ++count; return; } int main() { fun<int> (1); cout << endl; fun<int>(1); cout << endl; fun<double>(1.1); cout << endl; return 0; } A x = 1 count = 0 x = 1 count = 1 x = 1.1 count = 0 B x = 1 count = 0 x = 1 count = 0 x = 1.1 count = 0 C x = 1 count = 0 x = 1 count = 1 x = 1.1 count = 2 D-Compiler Error
A x = 1 count = 0 x = 1 count = 1 x = 1.1 count = 0 Compiler creates a new instance of a template function for every data type. So compiler creates two functions in the above example, one for int and other for double. Every instance has its own copy of static variable. The int instance of function is called twice, so count is incremented for the second call.
Can a destructor be virtual? Will the following program compile? #include <iostream> using namespace std; class Base { public: virtual ~Base() {} }; int main() { return 0; } A-Yes B-No
A destructor can be virtual. We may want to call appropriate destructor when a base class pointer points to a derived class object and we delete the object. If destructor is not virtual, then only the base class destructor may be called. For example, consider the following program. // Not good code as destructor is not virtual #include<iostream> using namespace std; class Base { public: Base() { cout << "Constructor: Base" << endl; } ~Base() { cout << "Destructor : Base" << endl; } }; class Derived: public Base { public: Derived() { cout << "Constructor: Derived" << endl; } ~Derived() { cout << "Destructor : Derived" << endl; } }; int main() { Base *Var = new Derived(); delete Var; return 0; } Output on GCC: Constructor: Base Constructor: Derived Destructor : Base
Predict the output of following C++ program #include<iostream> using namespace std; class Empty {}; int main() { cout << sizeof(Empty); return 0; } A non-zero value B- 0 C-Compiler Error D-Runtime Error
A non-zero value Size of an empty class is not zero. It is 1 byte generally. It is nonzero to ensure that the two different objects will have different addresses.
Output of following C++ program? #include<iostream> using namespace std; int main() { int x = 10; int& ref = x; ref = 20; cout << "x = " << x << endl ; x = 30; cout << "ref = " << ref << endl; return 0; } A-x = 20 ref = 30 B-x = 20 ref = 20 C-x = 10 ref = 30 D-x = 30 ref = 30
A) X= 20 ; Ref = 30 ref is an alias of x, so if we change either of them, we can see the change in other as well.
Output of C++ program? #include <iostream> int const s=9; int main() { std::cout << s; return 0; } Run on IDE Contributed by Pravasi Meet A- 9 B-Compiler Error
A- 9 The above program compiles & runs fine. Const keyword can be put after the variable name or before variable name. But most programmers prefer to put const keyword before the variable name.
Which of the following is true about pure virtual functions? 1) Their implementation is not known in a class where they are declared. 2) If a class has a pure virtual function, then the class becomes abstract class and an instance of this class cannot be created. A-Both 1 and 2 B-Only 1 C-Only 2 D-Neither 1 nor 2
A- Both 1 and 2
#include<iostream> using namespace std; class Base { protected: int a; public: Base() {a = 0;} }; class Derived1: public Base { public: int c; }; class Derived2: public Base { public: int c; }; class DerivedDerived: public Derived1, public Derived2 { public: void show() { cout << a; } }; int main(void) { DerivedDerived d; d.show(); return 0; } A- Compiler Error in Line "cout << a;" B -0 C -Compiler Error in Line "class DerivedDerived: public Derived1, public Derived2"
A- Compiler Error in Line "cout << a;" This is a typical example of diamond problem of multiple inheritance. Here the base class member 'a' is inherited through both Derived1 and Derived2. So there are two copies of 'a' in DerivedDerived which makes the statement "cout << a;" ambiguous. The solution in C++ is to use virtual base classes. For example, the following program works fine and prints [sourcecode language="CPP"] #include using namespace std; class Base { protected: int a; public: Base() {a = 0;} }; class Derived1: virtual public Base { public: int c; }; class Derived2: virtual public Base { public: int c; }; class DerivedDerived: public Derived1, public Derived2 { public: void show() { cout << a; } }; int main(void) { DerivedDerived d; d.show(); return 0; } [/sourcecode]
#include <stdio.h> int main() { const int x; x = 10; printf("%d", x); return 0; } Run on IDE A-Compiler Error B-10 C-0 D-Runtime Error
A- Compiler error One cannot change the value of 'const' variable except at the time of initialization. Compiler does check this.
Predict the output of following C++ program #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(); // Note the use of scope resolution here return 0; } A-In Base B-In Derived C-Compiler Error D-Runtime Error
A- In Base A base class function can be accessed with scope resolution operator even if the function is virtual.
Predict the output of following C++ program. Assume that there is no alignment and a typical implementation of virtual functions is done by the compiler. #include <iostream> using namespace std; class A { public: virtual void fun(); }; class B { public: void fun(); }; int main() { int a = sizeof(A), b = sizeof(B); if (a == b) cout << "a == b"; else if (a > b) cout << "a > b"; else cout << "a < b"; return 0; } A- a > b B -a == b C -a < b D-Compiler Error
A- a>b Class A has a VPTR which is not there in class B. In a typical implementation of virtual functions, compiler places a VPTR with every object. Compiler secretly adds some code in every constructor to this.
Output of following program? #include<iostream> using namespace std; class Point { Point() { cout << "Constructor called"; } }; int main() { Point t1; return 0; } A-Compiler Error B-Runtime Error C-Constructor called
A-Compiler Error By default all members of a class are private. Since no access specifier is there for Point(), it becomes private and it is called outside the class when t1 is constructed in main.
Predict the output? #include <iostream> using namespace std; class Test { int x; Test() { x = 5;} }; int main() { Test *t = new Test; cout << t->x; } A-Compiler Error B-5 C-Garbage Value D-0
A-Compiler Error There is compiler error: Test::Test() is private. new makes call to the constructor. In class Test, constructor is private (note that default access is private in C++).
#include<iostream> using namespace std; class Base1 { public: char c; }; class Base2 { public: int c; }; class Derived: public Base1, public Base2 { public: void show() { cout << c; } }; int main(void) { Derived d; d.show(); return 0; } A-Compiler Error in "cout << c;" B-Garbage Value C-Compiler Error in "class Derived: public Base1, public Base2"
A-Compiler Error in "cout << c;" The variable 'c' is present in both super classes of Derived. So the access to 'c' is ambiguous. The ambiguity can be removed by using scope resolution operator. 1 #include using namespace std; class Base1 { public: char c; }; class Base2 { public: int c; }; class Derived: public Base1, public Base2 { public: void show() { cout << Base2::c; } }; int main(void) { Derived d; d.show(); return 0; } [/sourcecode]
According to the C++11 standard, what is the output of this program? #include <iostream> int main() { void * p = &p; std::cout << bool(p); }
ANSWER "1" As defined in §3.3.2¶1, the point of name declaration is after its complete declarator and before its initialisation. This means that line 4 is valid C++, because it's possible to initialise the variable p with the address of an existing variable, even if it is its own address. The value of p is unknown, but can not be a null pointer value. The cast must thus evaluate to 1 and initialise the temporary bool as true.
Like constructors, can there be more than one destructors in a class? A Yes B No
NO There can be only one destructor in a class. Destructor's signature is always ~ClassNam() and they can not be passed arguments.
If you have an array of characters allocated with new. Which of the following is the best way to modify the size of the array? Use the realloc function from libc Delete the existing array, then allocate a new array and copy the data from the old array to the new array Allocate a new array, copy the data from old array to the new array and then delete the old array - correct It is not possible to do such an operation in C++
Allocate a new array, copy the data from old array to the new array and then delete the old array - correct description: You can not use realloc, because realloc may call free on memory allocated with new which is bad. You can do the same thing realloc does manually, but make sure not to delete the original array until after copying the data. Also you may want to check the size of the new array. If the new array is smaller than the old one, you may not need to do the reallocation depeding on the business logic.
According to the C++11 standard, what is the output of this program? #include <iostream> using namespace std; size_t get_size_1(int* arr) { return sizeof arr; } size_t get_size_2(int arr[]) { return sizeof arr; } size_t get_size_3(int (&arr)[10]) { return sizeof arr; } int main() { int array[10]; cout << (sizeof(array) == get_size_1(array)); cout << (sizeof(array) == get_size_2(array)); cout << (sizeof(array) == get_size_3(array)); }
Answer This question The program is guaranteed to output:. Its output is "001". Explanation This question compares three ways for a function to take an array as parameter, while two of them are actually the same. In main, the array is of array type, therefore the sizeof operator returns the size of the array in terms of bytes. (§5.3.3¶2 in the standard: "When applied to an array, the result [of the sizeof operator] is the total number of bytes in the array. This implies that the size of an array of n elements is n times the size of an element.") In get_size_3, the parameter is a reference to an array of size 10, therefore the sizeof operator returns the size of the array in terms of bytes. (§5.3.3¶2 in the standard: When applied to a reference or a reference type, the result is the size of the referenced type. ) In get_size_1 and get_size_2, the parameter is a pointer, therefore the sizeof operator returns the size of the pointer. Although the parameter of get_size_2 is an array, it is adjusted into a pointer. (§8.3.5¶5 in the standard: "any parameter of type "array of T" (...) is adjusted to be "pointer to T"" )
According to the C++11 standard, what is the output of this program? #include <iostream> #include <utility> struct A { A() { std::cout << "1"; } A(const A&) { std::cout << "2"; } A(A&&) { std::cout << "3"; } }; struct B { A a; B() { std::cout << "4"; } B(const B& b) : a(b.a) { std::cout << "5"; } B(B&& b) : a(b.a) { std::cout << "6"; } }; int main() { B b1; B b2 = std::move(b1); }
Answer This question The program is guaranteed to output:. Its output is "1426". Explanation First, b1 is default initialized. All members are initialized before the body of the constructor, so b1.a is default initialized first, and we get the output 14. §12.6.2¶8 in the standard: "In a non-delegating constructor, if a given non-static data member or base class is not designated by a mem-initializer-id (...) then if the entity is a non-static data member that has a brace-or-equal-initializer, the entity is initialized as specified in §8.5 (...) otherwise, the entity is default-initialized." Then, b2 is initialized with the move construcor (since std::move(b1)converts the reference to b1 to an xvalue, allowing it to be moved from.) In B's move constructor, a is initialized in the initializer list. Even though a is an rvalue reference (and bound to an rvalue), a itself is an lvalue, and cannot be moved from. b2.a is then copy initialized, printing 2, and finally the body of B's move constructor prints 6.
int i = 1; if (--i==1) { cout << i; } else { cout << i-1; } return 0; } A. It prints: 0 B. It prints: 1 C. It prints: -1 D. It prints: 2
Answer: C
An inline function can execute faster than a normal function. A - True B - False
Answer : A Explaination As the code of inline function gets expanded at the line of call, therefore it gets executed faster with no overhead of context switch
Class function which is called automatically as soon as the object is created is called as __ A - Constructor B - Destructor C - Friend function D - Inline function.
Answer : A Explaination If not provided the same, default constructor from the compiler is called automatically otherwise the programmer's provided constructor gets called.
What is the output of the following program? #include<isotream> #include<string.h> using namespace std; main() { char s[]="Hello\0Hi"; Cout<<strlen(s)<<" "<<sizeof(s); } A - 5 9 B - 7 20 C - 5 20 D - 8 20
Answer : A Explaination Length of the string is count of character upto '\0'. sizeof - reports the size of the array. #include<isotream> #include<string.h> using namespace std; main() { char s[]="Hello\0Hi"; Cout<<strlen(s)<<" "<<sizeof(s); }
A user defined header file is included by following statement in general. A - #include "file.h" B - #include <file.h> C - #include <file> D - #include file.h
Answer : A Explaination With the syntax as in (a) the compiler first looks for the file in the present working directory and then in the default include path if not found.
HAS-A relationship between the classes is shown through. A - Inheritance B - Container classes C - Polymorphism D - None of the above.
Answer : B Explaination A class containing anther class object as its member is called as container class and exhibits HAS A relationship.
What is the output of the following program? #include<isotream> using namespace std; void f() { static int i = 3; cout<<i; if(--i) f(); } main() { f(); } A - 3 2 1 0 B - 3 2 1 C - 3 3 3 D - Compile error
Answer : B Explaination As the static variable retains its value from the function calls, the recursion happens thrice.
Operators sizeof and ?: A - Both can be overloaded B - Both cannot be overloaded C - Only sizeof can be overloaded D - Only ?: can be overloaded Show Answer
Answer : B Explaination Both the mentioned operators cannot be overloaded.
In the following program f() is overloaded. void f(int x) { } int f(signed x) { return 1; } main() { } A - True B - False
Answer : B Explaination No, as both the functions arguments is same and compiler ignores return type to consider overloading though different in return type.
What is the output of the following program? #include<isotream> using namespace std; class Base { public: virtual void f() { cout<<"Base\n"; } }; class Derived:public Base { public: void f() { cout<<"Derived\n"; } }; main() { Base *p = new Derived(); p->f(); } A - Base B - Derived C - Compile error D - None of the above.
Answer : B Explaination The overridden method f() of the created object for derived class gets called. #include<isotream> using namespace std; class Base { public: virtual void f() { cout<<"Base\n"; } }; class Derived:public Base { public: void f() { cout<<"Derived\n"; } }; main() { Base *p = new Derived(); p->f(); }
What is the output of the following program? #include<isotream> using namespace std; class abc { public: int i; abc(int i) { i = i; } }; main() { abc m(5); cout<<m.i; } A - 5 B - Garbage C - Error at the statement i=i; D - Compile error: 'i' declared twice.
Answer : B Explaination i=i, is assigning member variable to itself. #include<isotream> using namespace std; class abc { public: int i; abc(int i) { i = i; } }; main() { abc m(5); cout<<m.i; }
Objects created using new operator are stored in __ memory. A - Cache B - Heap C - Stack D - None of the above.
Answer : B Explaination new operator allocates memory dynamically know as Heap/free memory.
(i) 'ios' is the base class of 'istream' (ii) All the files are classified into only 2 types. (1) Text Files (2) Binary Files. A - Only (i) is true B - Only (ii) is true C - Both (i) & (ii) are true D - Both (i) & (ii) are false
Answer : C Explaination
Special symbol permitted with in the identifier name. A - $ B - @ C - _ D - .
Answer : C Explaination The only permitted special symbol is under score (_) in the identifier.
What is the output of the following program? #include<isotream> using namespace std; void f() { static int i; ++i; cout<<i<<" "; } main() { f(); f(); f(); } A - 1 1 1 B - 0 0 0 C - 3 2 1 D - 1 2 3
Answer : D Explaination 1 2 3, A static local variables retains its value between the function calls and the default value is 0. #include<isotream> using namespace std; void f() { static int i; ++i; cout<<i<<" "; } main() { f(); f(); f(); }
What is the output of the following program? #include<isotream> using namespace std; void f() { static int i; ++i; cout<<i<<" "; } main() { f(); f(); f(); } A - 1 1 1 B - 0 0 0 C - 3 2 1 D - 1 2 3
Answer : D Explaination 1 2 3, A static local variables retains its value between the function calls and the default value is 0. #include<isotream> using namespace std; void f() { static int i; ++i; cout<<i<<" "; } main() { f(); f(); f(); } Hide Answer
What is the output of the following program? #include<isotream> using namespace std; main() { int r, x = 2; float y = 5; r = y%x; cout<<r; } A - 1 B - 0 C - 2 D - Compile error
Answer : D Explaination Answer Compile Error, It is invalid that either of the operands for the modulus operator (%) is a real number. #include<isotream> using namespace std; main() { int r, x = 2; float y = 5; r = y%x; cout<<r; }
What is the output of the following program? #include<isotream> using namespace std; main() { int r, x = 2; float y = 5; r = y%x; cout<<r; } A - 1 B - 0 C - 2 D - Compile error
Answer : D Explaination Answer Compile Error, It is invalid that either of the operands for the modulus operator (%) is a real number. #include<isotream> using namespace std; main() { int r, x = 2; float y = 5; r = y%x; cout<<r; } Hide Answer
What is the output of the following program? #include<isotream> using namespace std; main() { class student { int rno = 10; } v; cout<<v.rno; } A - 10 B - Garbage C - Runtime error D - Compile error
Answer : D Explaination Class member variables cannot be initialized. #include<isotream> using namespace std; main() { class student { int rno = 10; } v; cout<<v.rno; }
What is the output of the following program? #include<isotream> using namespace std; main() { const int a = 5; a++; cout<<a; } A - 5 B - 6 C - Runtime error D - Compile error Show Answer
Answer : D Explaination Compile error - constant variable cannot be modified. #include<isotream> using namespace std; main() { const int a = 5; a++; cout<<a; }
The copy constructor is executed on A - Assigned one object to another object at its creation B - When objects are sent to function using call by value mechanism C - When the function return an object D - All the above.
Answer : D Explaination Options (a), (b) & (c) are applicable.
Which operator is required to be overloaded as member function only? A - _ B - _ _ C - ++ (postfix version) D - =
Answer : D Explaination Overloaded assignment operator does the job similar to copy constructor and is required to be overloaded as member function of the class.
The following operator can be used to calculate the value of one number raised to another. A - ^ B - ** C - ^^ D -None of the above
Answer : D Explaination There is no such operator in C/C++.
What happens when you attempt to compile and run the following code? #include <iostream> #include <string> using namespace std; class A { protected: int y; public: int x; int z; A() { x=2; y=2; z=3; } A(int a, int b) : x(a), y(b) { z = x ? y;} void Print() { cout << z; } }; int main () { A a(2,5); a.Print(); return 0; } A. It prints: ?3 B. It prints: 2 C. It prints: 6 D. It prints: 5
Answer A
What happens when you attempt to compile and run the following code? #include <iostream> using namespace std; int main(int argc, char *argv[]) { char *s = "ABCDEF"; cout << s+2; return 0; } A. It prints: CDEF B. It prints: ABCDEF C. It prints: BCDEF D. None of these
Answer A
What happens when you attempt to compile and run the following code? #include <iostream> #include <cstdarg> using namespace std; int mult(int f, int s, int t); int main() { cout << mult(1,2,3); return 0; } int mult(int f, int s, int t) { int mult_res; mult_res = f*s*t; return mult_res; } A. It prints: 0 B. It prints: 6 C. It prints: 2 D. It prints: 3
Answer B
What happens when you attempt to compile and run the following code? #include <iostream> using namespace std; class A { public: void Print(){ cout<<"A";} }; class B:public A { public: void Print(){ cout<< "B";} }; int main() { A *obj; A ob1; obj = &ob1; obj?>Print(); B ob2; obj = &ob2; obj?>Print(); } A. It prints: AB B. It prints: AA C. It prints: BA D. It prints: BB
Answer B
What happens when you attempt to compile and run the following code? #include <iostream> using namespace std; void fun(int*); int main() { int i=2; fun(&i); cout<<i; return 0; } void fun(int *i) { *i = *i**i; } A. It prints: 1 B. It prints: 4 C. It prints: 10 D. It prints: 0
Answer B
Which, if any, of the member function definitions below are ill-formed? #include <iostream> int g_x = 44; struct Foo { int m_x; static int s_x; Foo(int x) : m_x(x) {} int a(int x = g_x) { return x + 1; } int b(int x = m_x) { return x + 1; } int c(int x = s_x) { return x + 1; } }; int Foo::s_x = 22; int main(int argc, char** argv) { Foo f(6); std::cout << f.a() << std::endl; std::cout << f.b() << std::endl; std::cout << f.c() << std::endl; return 0; } a- a b- b c- c d- a and b e- none
Answer B description: b is ill-formed. Non-static members can not be used as default arguments.
What happens when you attempt to compile and run the following code? #include <iostream> #include <string> using namespace std; class A { int x; protected: int y; public: int z; }; class B : public A { string name; public: void set() { y = 2; z = 3; } void Print() { cout << y << z; } }; int main () { B b; b.set(); b.Print(); return 0; } A. It prints: 123 B. It prints: 000 C. It prints: 23 D. It prints: 12
Answer C
What happens when you attempt to compile and run the following code? #include <iostream> using namespace std; class First { public: void Print(){ cout<<"from First";} }; class Second { public: void Print(){ cout<< "from Second";} }; int main() { First FirstObject; FirstObject.Print(); Second SecondObject; SecondObject.Print(); } A. It prints: from First B. It prints: from Firstfrom First C. It prints: from Firstfrom Second D. It prints: from Secondfrom Second
Answer C
What happens when you attempt to compile and run the following code? #include <iostream> using namespace std; int fun(int x); int main() { cout << fun(0); return 0; } int fun(int x) { if(x > 0) return fun(x-1); else return 100; } A. It prints: 0 B. It prints: 10 C. It prints: 100 D. It prints: -1
Answer C
What happens when you attempt to compile and run the following code? #include <iostream> using namespace std; int main() { int x=2, *y; y = &x; cout << *y + x; return 0; } A. It prints: 1 B. It prints: 2 C. It prints: 4 D. It prints: 0
Answer C
What happens when you attempt to compile and run the following code? #include <iostream> using namespace std; int main(){ int *i; i = new int; *i = 1.0 / 2 * 2 / 1 * 2 / 4 * 4; cout << *i; return 0; } A. It prints: 0 B. It prints: 1 C. It prints: 2 D. It prints: 0.5
Answer C
What happens when you attempt to compile and run the following code? #include <iostream> using namespace std; void fun(int &i); int main() { int i=2; fun(i); cout<<i; return 0; } void fun(int &i) { i+=2; } A. It prints: 2 B. It prints: 0 C. It prints: 4 D. It prints: 16
Answer C
What does the following statement mean? int (*fp)(char*) A. pointer to a pointer B. pointer to an array of chars C. pointer to function taking a char* argument and returns an int D. function taking a char* argument and returning a pointer to int
Answer: Option C Explanation: pointer to function taking a char* argument and returns an int
Output of following program? #include<iostream> using namespace std; class Point { public: Point() { cout << "Normal Constructor called\n"; } Point(const Point &t) { cout << "Copy constructor called\n"; } }; int main() { Point *t1, *t2; t1 = new Point(); t2 = new Point(*t1); Point t3 = *t1; Point t4; t4 = t3; return 0; } Run on IDE A- Normal Constructor called Normal Constructor called Normal Constructor called Copy Constructor called Copy Constructor called Normal Constructor called Copy Constructor called B- Normal Constructor called Copy Constructor called Copy Constructor called Normal Constructor called Copy Constructor called C-Normal Constructor called Copy Constructor called Copy Constructor called Normal Constructor called
Answer C See following comments for explanation: Point *t1, *t2; // No constructor call t1 = new Point(10, 15); // Normal constructor call t2 = new Point(*t1); // Copy constructor call Point t3 = *t1; // Copy Constructor call Point t4; // Normal Constructor call t4 = t3; // Assignment operator call
What happens when you attempt to compile and run the following code? #include <iostream> using namespace std; class BaseClass { public: int *ptr; BaseClass(int i) { ptr = new int(i); } ~BaseClass() { delete ptr; delete ptr;} void Print() { cout << *ptr; } }; void fun(BaseClass x); int main() { BaseClass o(10); fun(o); o.Print(); } void fun(BaseClass x) { cout << "Hello:"; } A. It prints: Hello:1 B. It prints: Hello: C. It prints: 10 D. Runtime error.
Answer D
What is the output of the program if character 2 is supplied as input? #include <iostream> using namespace std; int main () { int c; cin >> c; try { switch (c) "Pass Any Exam. Any Time." - 100% Pass Guarantee! 53C++ Institute CPA Exam { case 1: throw 20; case 2: throw 5.2f; } } catch (int e) { cout << "int exception. Exception Nr. " << e; } catch (float e) { cout << "float exception. Exception Nr. " << e; } catch (...) { cout << "An exception occurred."; } return 0; } A. It prints: float exception. Exception Nr. B. It prints: int exception. Exception Nr. 20 C. It prints: An exception occurred D. It prints: float exception. Exception Nr. 5.2
Answer D
What is the output of the program if character 4 is supplied as input? #include <iostream> using namespace std; int main () { int c; cin >> c; try { switch (c) { case 1: throw 20; case 2: throw 5.2f; case 3: throw 'a'; default: cout<<"No exception"; } } catch (int e) { cout << "int exception. Exception Nr. " << e; } catch (float e) { cout << "float exception. Exception Nr. " << e; } catch (...) { cout << "An exception occurred."; } return 0; } A. It prints: float exception. Exception Nr. B. It prints: int exception. Exception Nr. C. It prints: An exception occurred D. It prints: No exception
Answer D
Which code, inserted at line 14, generates the output "3.14 10"? #include <iostream> using namespace std; namespace myNamespace1 { int x = 5; int y = 10; } namespace myNamespace2 { float x = 3.14; float y = 1.5; } int main () { //insert code here cout << x << " " << y; return 0; } A. using myNamespace2::y; using myNamespace1::x; B. using namespace myNamespace1; C. using namespace myNamespace1; using namespace myNamespace2; D. using myNamespace1::y; using myNamespace2::x;
Answer D
Which code, inserted at line 8, generates the output "0102020"? #include <iostream> using namespace std; class Base { static int age; public: Base () {}; ~Base () {}; //insert code here void Print() { cout << age;} }; int Base::age=0; int main () { Base a,*b; b = new Base(); a.Print(); a.setAge(10); a.Print(); b?>setAge(); a.Print(); b?>Print(); return 0; } A. void setAge(int a) {age = a;} B. void setAge() {age = 20;} C. void setAge() {age = 10;} D. void setAge(int a=20) {age = a;}
Answer D;
In a group of nested loops, which loop is executed the most number of times? [a] the outermost loop [b] the innermost loop [c] all loops are executed the same number of times [d] cannot be determined without knowing the size of the loops
Answer is B
What's wrong? while( (i < 10) && (i > 24)) [a] the logical operator && cannot be used in a test condition [b] the while loop is an exit-condition loop [c] the test condition is always false [d] the test condition is always true
Answer is C
What is the output of the program? #include <iostream> #include <string> using namespace std; int main() { string s1[]= {"Hello" , "World" }; for (int i=0; i<2; i++) { cout << s1[i]; } return( 0 ); } A. It prints: HelloWorld B. It prints: Hello C. It prints: WorldHello D. It prints: World
Answer: A
How could you pass arguments to functions? A. by value B. by reference C. by pointer D. by void
Answer: A,B,C
Which of the following can be checked in a switch?case statement? A. char B. int C. enum D. double
Answer: A,B,C
Which of the following statements are correct about an array? int tab[10]; A. The array can store 10 elements. B. The expression tab[1] designates the very first element in the array. C. The expression tab[9] designates the last element in the array. D. It is necessary to initialize the array at the time of declaration.
Answer: A,C
Which code, inserted at line 5, generates the output "ABC"? #include <iostream> using namespace std; class A { public: //insert code here }; class B:public A { public: void Print(){ cout<< "B"; } }; class C:public B { public: void Print(){ cout<< "C"; } }; int main() { A ob1; B ob2; C ob3; A *obj; obj = &ob1; obj?>Print(); obj = &ob2; obj?>Print(); obj = &ob3; obj?>Print(); } A. void Print(){ cout<<"A";} B. virtual void Print(){ cout<<"A";} C. virtual void Print(string s){ cout<<s;} D. None of these
Answer: B
Which of the following is a logical operator? A. & B. && C. || D. !
Answer: B,C,D
Output of following program. #include <iostream> using namespace std; template <class T, int max> int arrMin(T arr[], int n) { int m = max; for (int i = 0; i < n; i++) if (arr[i] < m) m = arr[i]; return m; } int main() { int arr1[] = {10, 20, 15, 12}; int n1 = sizeof(arr1)/sizeof(arr1[0]); char arr2[] = {1, 2, 3}; int n2 = sizeof(arr2)/sizeof(arr2[0]); cout << arrMin<int, 10000>(arr1, n1) << endl; cout << arrMin<char, 256>(arr2, n2); return 0; } A Compiler error, template argument must be a data type. B 10 1 C 10000 256 D 1 1
B 10 1 We can pass non-type arguments to templates. Non-type parameters are mainly used for specifying max or min values or any other constant value for a particular instance of template. The important thing to note about non-type parameters is, they must be const. Compiler must know the value of non-type parameters at compile time. Because compiler needs to create functions/classes for a specified non-type value at compile time. Following is another example of non-type parameters. #include <iostream> using namespace std; template < class T, int N > T fun (T arr[], int size) { if (size > N) cout << "Not possible"; T max = arr[0]; for (int i = 1; i < size; i++) if (max < arr[i]) max = arr[i]; return max; } int main () { int arr[] = {12, 3, 14}; cout << fun (arr, 3); }
What happens in C++ when an exception is thrown and not caught anywhere like following program. #include <iostream> using namespace std; int fun() throw (int) { throw 10; } int main() { fun(); return 0; } A Compiler error B Abnormal program termination C Program doesn't print anything and terminates normally D None of the above
B Abnormal program termination When an exception is thrown and not caught, the program terminates abnormally.
#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; } A-Compiler Dependent B Base1′s constructor called Base2′s constructor called Derived's constructor called C Base2′s constructor called Base1′s constructor called Derived's constructor called D-Compiler Error
B Base1′s constructor called Base2′s constructor called Derived's constructor called When a class inherits from multiple classes, constructors of base classes are called in the same order as they are specified in inheritance.
Output? #include <iostream> using namespace std; template <class T> T max (T &a, T &b) { return (a > b)? a : b; } template <> int max <int> (int &a, int &b) { cout << "Called "; return (a > b)? a : b; } int main () { int a = 10, b = 20; cout << max <int> (a, b); } A 20 B Called 20 C Compiler Error
B Called 20 Above program is an example of template specialization. Sometime we want a different behaviour of a function/class template for a particular data type. For this, we can create a specialized version for that particular data type.
Output of following program #include<iostream> using namespace std; class Base {}; class Derived: public Base {}; int main() { Derived d; try { throw d; } catch(Base b) { cout<<"Caught Base Exception"; } catch(Derived d) { cout<<"Caught Derived Exception"; } return 0; } A Caught Derived Exception B Caught Base Exception C Compiler Error
B Caught Base Exception If both base and derived classes are caught as exceptions then catch block of derived class must appear before the base class. If we put base class first then the derived class catch block will never be reached. In Java, catching a base class exception before derived is not allowed by the compiler itself. In C++, compiler might give warning about it, but compiles the code.
#include <iostream> using namespace std; int main() { int x = -1; try { cout << "Inside try \n"; if (x < 0) { throw x; cout << "After throw \n"; } } catch (int x ) { cout << "Exception Caught \n"; } cout << "After catch \n"; return 0; } A Inside try Exception Caught After throw After catch B Inside try Exception Caught After catch C Inside try Exception Caught D Inside try After throw After catch
B Inside try Exception Caught After catch When an exception is thrown, lines of try block after the throw statement are not executed. When exception is caught, the code after catch block is executed. Catch blocks are generally written at the end through.
What is the difference between struct and class in C++? A All members of a structure are public and structures don't have constructors and destructors B Members of a class are private by default and members of struct are public by default. When deriving a struct from a class/struct, default access-specifier for a base class/struct is public and when deriving a class, default access specifier is private. C All members of a structure are public and structures don't have virtual functions D- All of the above
B Members of a class are private by default and members of struct are public by default. When deriving a struct from a class/struct, default access-specifier for a base class/struct is public and when deriving a class, default access specifier is private.
Which of the following statements are correct about the structure declaration given below? struct Book { private String name; protected int totalpages; public Single price; public void Showdata() { Console.WriteLine(name + " " + totalpages + " " + price); } Book() { name = " "; totalpages = 0; price = 0.0f; } } Book b = new Book(); 1.We cannot declare the access modifier of totalpages as protected. 2.We cannot declare the access modifier of name as private. 3.We cannot define a zero-argument constructor inside a structure. 4.We cannot declare the access modifier of price as public. 5.We can define a Showdata() method inside a structure. A) 1, 2 B) 1, 3, 5 C) 2, 4 D) 3, 4, 5
B) 1, 3, 5
Output of following program? Assume that the size of char is 1 byte and size of int is 4 bytes, and there is no alignment done by the compiler. #include<iostream> #include<stdlib.h> using namespace std; template<class T, class U> class A { T x; U y; static int count; }; int main() { A<char, char> a; A<int, int> b; cout << sizeof(a) << endl; cout << sizeof(b) << endl; return 0; } A 6 12 B 2 8 C Compiler Error: There can not be more than one template arguments. D 8 8
B- 2 8 Since count is static, it is not counted in sizeof.
Assume that an integer takes 4 bytes and there is no alignment in following classes, predict the output. #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; } A- 40 B-80 C-0 D-4
B- 80 Since b1 and b2 both inherit from class base, two copies of class base are there in class derived. This kind of inheritance without virtual causes wastage of space and ambiguities. virtual base classes are used to save space and avoid ambiguities in such cases. For example, following program prints 48. 8 extra bytes are for bookkeeping information stored by the compiler (See this for details) #include<iostream> using namespace std; class base { int arr[10]; }; class b1: virtual public base { }; class b2: virtual public base { }; class derived: public b1, public b2 {}; int main(void) { cout << sizeof(derived); return 0; }
#include<iostream> using namespace std; class Base { public: int fun() { cout << "Base::fun() called"; } int fun(int i) { cout << "Base::fun(int i) called"; } }; class Derived: public Base { public: int fun() { cout << "Derived::fun() called"; } }; int main() { Derived d; d.Base::fun(5); return 0; } A- Compiler Error B- Base::fun(int i) called
B- Base::fun(int i) called We can access base class functions using scope resolution operator even if they are made hidden by a derived class function.
Predict the output of following program? #include <iostream> using namespace std; class Test { private: int x; public: Test(int i) { x = i; cout << "Called" << endl; } }; int main() { Test t(20); t = 30; // conversion constructor is called here. return 0; } A-Compiler Error B-Called Called C- Called
B- Called Called Explanation If a class has a constructor which can be called with a single argument, then this constructor becomes conversion constructor because such a constructor allows automatic conversion to the class being constructed. A conversion constructor can be called anywhere when the type of single argument is assigned to the object. The output of the given program is Called Called
Predict the output of following program. #include <iostream> using namespace std; class A { protected: int x; public: A() {x = 0;} friend void show(); }; class B: public A { public: B() : y (0) {} private: int y; }; void show() { A a; B b; cout << "The default value of A::x = " << a.x << " "; cout << "The default value of B::y = " << b.y; } A- Compiler Error in show() because x is protected in class A B- Compiler Error in show() because y is private in class b C- The default value of A::x = 0 The default value of B::y = 0 D- Compiler Dependent
B- Compiler Error in show() because y is private in class b Please note that show() is a friend of class A, so there should not be any compiler error in accessing any member of A in show(). Class B is inherited from A, the important point to note here is friendship is not inherited. So show() doesn't become a friend of B and therefore can't access private members of B.
Output? #include <iostream> using namespace std; template<int n> struct funStruct { static const int val = 2*funStruct<n-1>::val; }; template<> struct funStruct<0> { static const int val = 1 ; }; int main() { cout << funStruct<10>::val << endl; return 0; } A-Compiler Error B-1024 C-2 D-1
B-1024 This is an example of template metaprogramming. The program mainly calculates 2^10.
Predict the output of following C++ program. #include <iostream> using namespace std; class A { private: int x; public: A(int _x) { x = _x; } int get() { return x; } }; class B { static A a; public: static int get() { return a.get(); } }; int main(void) { B b; cout << b.get(); return 0; } A 0 B Compiler Error: Undefined reference B::a C Compiler Error: Cannot access static a D Compiler Error: multiple functions with same name get()
B- Compiler Error: Undefined reference B::a There is a compiler error because static member a is not defined in B. To fix the error, we need to explicitly define a. The following program works fine. #include <iostream > using namespace std; class A { private: int x; public: A(int _x) { x = _x; } int get() { return x; } }; class B { static A a; public: static int get() { return a.get(); } }; A B::a(0); int main(void) { B b; cout << b.get(); return 0; }
Which of the following functions must use reference. A-Assignment operator function B-Copy Constructor C-Destructor D-Parameterized constructor
B- Copy Constructor A copy constructor is called when an object is passed by value. Copy constructor itself is a function. So if we pass argument by value in a copy constructor, a call to copy constructor would be made to call copy constructor which becomes a non-terminating chain of calls. Therefore compiler doesn't allow parameters to be pass by value.
Predict the output of following program. #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; } A- Constructor called B- Empty C- Compiler Error D- Runtime error
B- Empty Unlike new, malloc() doesn't call constructor If we replace malloc() with new, the constructor is called.
Output? #include<iostream> #include<string.h> using namespace std; class String { char *str; public: String(const char *s); void change(int index, char c) { str[index] = c; } char *get() { return str; } }; String::String(const char *s) { int l = strlen(s); str = new char[l+1]; strcpy(str, s); } int main() { String s1("geeksQuiz"); String s2 = s1; s1.change(0, 'G'); cout << s1.get() << " "; cout << s2.get(); } A-GeeksQuiz geeksQuiz B-GeeksQuiz GeeksQuiz C-geeksQuiz geeksQuiz D-geeksQuiz GeeksQuiz
B- GeeksQuiz GeeksQuiz Explanation: Since there is no copy constructor, the compiler creates a copy constructor. The compiler created copy constructor does shallow copy in line " String s2 = s1;" So str pointers of both s1 and s2 point to the same location. There must be a user defined copy constructor in classes with pointers to dynamic memory allocation.
#include<iostream> using namespace std; class P { public: void print() { cout <<" Inside P"; } }; class Q : public P { public: void print() { cout <<" Inside Q"; } }; class R: public Q { }; int main(void) { R r; r.print(); return 0; } Run on IDE A-Inside P B-Inside Q C-Compiler Error: Ambiguous call to print()
B- Inside Q The print function is not present in class R. So it is looked up in the inheritance hierarchy. print() is present in both classes P and Q, which of them should be called? The idea is, if there is multilevel inheritance, then function is linearly searched up in the inheritance hierarchy until a matching function is found.
What happens when a function throws an error but doesn't specify it in the list of exceptions it can throw. For example, what is the output of following program? #include <iostream> using namespace std; // Ideally it should have been "int fun() (int)" int fun() { throw 10; } int main() { try { fun(); } catch (int ) { cout << "Caught"; } return 0; } A-Compiler Error B-No compiler Error. Output is "Caught"
B- No compiler Error. Output is "Caught". C++ compiler doesn't check enforce a function to list the exceptions that it can throw. In Java, it is enforced. It is up to the programmer to specify. Being a civilized programmer, a programmer should specify the list.
Predict the output of following C++ program? #include<iostream> using namespace std; class Test { private: int x; public: Test() {x = 0;} void destroy() { delete this; } void print() { cout << "x = " << x; } }; int main() { Test obj; obj.destroy(); obj.print(); return 0; } A- x = 0 B-undefined behavior C-compiler error
B- Undefined Behavior delete operator works only for objects allocated using operator new. If the object is created using new, then we can do delete this, otherwise behavior is undefined. See "delete this" in C++ for more examples.
#include <iostream> using namespace std; class Point { int x, y; public: Point(int i = 0, int j = 0) { x = i; y = j; } int getX() { return x; } int getY() { return y; } }; int main() { Point p1; Point p2 = p1; cout << "x = " << p2.getX() << " y = " << p2.getY(); return 0; } A- Compiler Error B- x = 0 y = 0 C- x = garbage value y = garbage value
B- x= 0, y = 0 Compiler creates a copy constructor if we don't write our own. Compiler writes it even if we have written other constructors in class. So the above program works fine. Since we have default arguments, the values assigned to x and y are 0 and 0.
What is the advantage of exception handling? 1) Remove error-handling code from the software's main line of code. 2) A method writer can chose to handle certain exceptions and delegate others to the caller. 3) An exception that occurs in a function can be handled anywhere in the function call stack. A-Only 1 B-1, 2 and 3 C-1 and 3 D-1 and 2
B-1, 2 and 3
Which of the following is true about exception handling in C++? 1) There is a standard exception class like Exception class in Java. 2) All exceptions are unchecked in C++, i.e., compiler doesn't check if the exceptions are caught or not. 3) In C++, a function can specify the list of exceptions that it can throw using comma separated list like following. void fun(int a, char b) throw (Exception1, Exception2, ..) A-1 and 3 B-1, 2 and 3 C-1 and 2 D-2 and 3
B-1, 2 and 3
#include<iostream> using namespace std; int &fun() { int x = 10; return x; } int main() { fun() = 30; cout << fun(); return 0; } A-Compiler Error: Function cannot be used as lvalue B-10 C-30 D-0
B-10 When a function returns by reference, it can be used as lvalue. Since x is a local variable, every call to fun() will have use memory for x and call "fun() = 30" will not effect on next call.
Predict the output #include<iostream> using namespace std; class A { int i; public: A(int ii = 0) : i(ii) {} void show() { cout << i << endl; } }; class B { int x; public: B(int xx) : x(xx) {} operator A() const { return A(x); } }; void g(A a) { a.show(); } int main() { B b(10); g(b); g(20); return 0; } A-Compiler Error B-10 20 C 20 20 D 10 10
B-10 20 Note that the class B has as conversion operator overloaded, so an object of B can be converted to that of A. Also, class A has a constructor which can be called with single integer argument, so an int can be converted to A.
#include <iostream> using namespace std; class Player { private: int id; static int next_id; public: int getID() { return id; } Player() { id = next_id++; } }; int Player::next_id = 1; int main() { Player p1; Player p2; Player p3; cout << p1.getID() << " "; cout << p2.getID() << " "; cout << p3.getID(); return 0; } A Compiler Error B 1 2 3 C 1 1 1 D 3 3 3 E 0 0 0
B-123 If a member variable is declared static, all objects of that class have access to a single instance of that variable. Static variables are sometimes called class variables, class fields, or class-wide fields because they don't belong to a specific object; they belong to the class. In the above code, static variable next_id is used to assign a unique id to all objects.
Predict the output of following C++ progran #include <iostream> using namespace std; int i; class A { public: ~A() { i=10; } }; int foo() { i=3; A ob; return i; } int main() { cout << foo() << endl; return 0; } A-0 B-3 C-10 D-None of the above
B-3 While returning from a function, destructor is the last method to be executed. The destructor for the object "ob" is called after the value of i is copied to the return value of the function. So, before destructor could change the value of i to 10, the current value of i gets copied & hence the output is i = 3.
What is the return value of f(p, p) if the value of p is initialized to 5 before the call? Note that the first parameter is passed by reference, whereas the second parameter is passed by value. int f(int &x, int c) { c = c - 1; if (c == 0) return 1; x = x + 1; return f(x, c) * x; } A- 3024 B-6561 c-55440 D-161051
B-6561 Since c is passed by value and x is passed by reference, all functions will have same copy of x, but different copies of c. f(5, 5) = f(x, 4)*x = f(x, 3)*x*x = f(x, 2)*x*x*x = f(x, 1)*x*x*x*x = 1*x*x*x*x = x^4 Since x is incremented in every function call, it becomes 9 after f(x, 2) call. So the value of expression x^4 becomes 9^4 which is 6561. 1
Predict the output the of following program. #include <iostream> using namespace std; class B; class A { int a; public: A():a(0) { } void show(A& x, B& y); }; class B { private: int b; public: B():b(0) { } friend void A::show(A& x, B& y); }; void A::show(A& x, B& y) { x.a = 10; cout << "A::a=" << x.a << " B::b=" << y.b; } int main() { A a; B b; a.show(a,b); return 0; } A-Compiler Error B-A::a=10 B::b=0 C-A::a=0 B::b=0
B-A::a=10 B::b=0 This is simple program where a function of class A is declared as friend of class B. Since show() is friend, it can access private data members of B.
Predict the output of following program. #include<iostream> using namespace std; class Point { int x; public: Point(int x) { this->x = x; } Point(const Point p) { x = p.x;} int getX() { return x; } }; int main() { Point p1(10); Point p2 = p1; cout << p2.getX(); return 0; } A-10 B-Compiler Error: p must be passed by reference C- Garbage value D- None of the above
B-Compiler Error Objects must be passed by reference in copy constructors. Compiler checks for this and produces compiler error if not passed by reference. The following program compiles fine and produces output as 10. #include <iostream > using namespace std; class Point { int x; public: Point(int x) { this->x = x; } Point(const Point &p) { x = p.x;} int getX() { return x; } }; int main() { Point p1(10); Point p2 = p1; cout << p2.getX(); return 0; } The reason is simple, if we don't pass by reference, then argument p1 will be copied to p. So there will be a copy constructor call to call the copy constructor, which is not possible.
#include<iostream> using namespace std; class Base { public : int x, y; public: Base(int i, int j){ x = i; y = j; } }; class Derived : public Base { public: Derived(int i, int j):x(i), y(j) {} void print() {cout << x <<" "<< y; } }; int main(void) { Derived q(10, 10); q.print(); return 0; } A-10 10 B-Compiler Error C-0 0
B-Compiler Error The base class members cannot be directly assigned using initializer list. We should call the base class constructor in order to initialize base class members. Following is error free program and prints "10 10" 1 #include using namespace std; class Base { public : int x, y; public: Base(int i, int j){ x = i; y = j; } }; class Derived : public Base { public: Derived(int i, int j): Base(i, j) {} void print() {cout << x <<" "<< y; } }; int main(void) { Derived q(10, 10); q.print(); return 0; } [/sourcecode]
#include<iostream> using namespace std; class Base { public: void show() { cout<<" In Base "; } }; class Derived: public Base { public: int x; void show() { cout<<"In Derived "; } Derived() { x = 10; } }; int main(void) { Base *bp, b; Derived d; bp = &d; bp->show(); cout << bp->x; return 0; } A-Compiler Error in line " bp->show()" B-Compiler Error in line " cout << bp->x" C-In Base 10 D-In Derived 10
B-Compiler Error in line " cout << bp->x" Explanation: A base class pointer can point to a derived class object, but we can only access base class member or virtual functions using the base class pointer.
Predict the output of following program. #include<iostream> using namespace std; class Base { public: virtual void show() = 0; }; class Derived : public Base { }; int main(void) { Derived q; return 0; } A-Compiler Error: there cannot be an empty derived class B-Compiler Error: Derived is abstract C-No compiler Error
B-Compiler Error: Derived is abstract If we don't override the pure virtual function in derived class, then derived class also becomes abstract class.
Output? #include<iostream> using namespace std; class Base { private: int i, j; public: Base(int _i = 0, int _j = 0): i(_i), j(_j) { } }; class Derived: public Base { public: void show(){ cout<<" i = "<<i<<" j = "<<j; } }; int main(void) { Derived d; d.show(); return 0; } A- i = 0 j = 0 B-Compiler Error: i and j are private in Base C-Compiler Error: Could not call constructor of Base
B-Compiler Error: i and j are private in Base
#include <iostream> using namespace std; class Test { static int count; int id; public: Test() { count++; id = count; cout << "Constructing object number " << id << endl; if(id == 4) throw 4; } ~Test() { cout << "Destructing object number " << id << endl; } }; int Test::count = 0; int main() { try { Test array[5]; } catch(int i) { cout << "Caught " << i << endl; } } A Constructing object number 1 Constructing object number 2 Constructing object number 3 Constructing object number 4 Destructing object number 1 Destructing object number 2 Destructing object number 3 Destructing object number 4 Caught 4 B Constructing object number 1 Constructing object number 2 Constructing object number 3 Constructing object number 4 Destructing object number 3 Destructing object number 2 Destructing object number 1 Caught 4 C Constructing object number 1 Constructing object number 2 Constructing object number 3 Constructing object number 4 Destructing object number 4 Destructing object number 3 Destructing object number 2 Destructing object number 1 Caught 4 D Constructing object number 1 Constructing object number 2 Constructing object number 3 Constructing object number 4 Destructing object number 1 Destructing object number 2 Destructing object number 3 Caught 4
B-Constructing object number 1 Constructing object number 2 Constructing object number 3 Constructing object number 4 Destructing object number 3 Destructing object number 2 Destructing object number 1 Caught 4 The destructors are called in reverse order of constructors. Also, after the try block, the destructors are called only for completely constructed objects.
#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; } A-Base1's destructor Base2's destructor Derived's destructor B-Derived's destructor Base2's destructor Base1's destructor C-Derived's destructor D-Compiler Dependent
B-Derived's destructor Base2's destructor Base1's destructor Destructors are always called in reverse order of constructors.
Can static functions be virtual? Will the following program compile? #include<iostream> using namespace std; class Test { public: virtual static void fun() { } }; Run on IDE A-Yes B-No
B-NO
Can a constructor be virtual? Will the following program compile? #include <iostream> using namespace std; class Base { public: virtual Base() {} }; int main() { return 0; } A-Yes B-No
B-No There is nothing like Virtual Constructor. Making constructors virtual doesn't make sense as constructor is responsible for creating an object and it can't be delegated to any other object by virtual keyword means.
Is it fine to call delete twice for a pointer? #include<iostream> using namespace std; int main() { int *ptr = new int; delete ptr; delete ptr; return 0; } A-Yes B-No
B-No It is undefined behavior to call delete twice on a pointer. Anything can happen, the program may crash or produce nothing.
Which of the following is true? A All objects of a class share all data members of class B Objects of a class do not share non-static members. Every object has its own copy. C Objects of a class do not share codes of non-static methods, they have their own copy D None of the above
B-Objects of a class do not share non-static members. Every object has its own copy. Every object maintains a copy of non-static data members. For example, let Student be a class with data members as name, year, batch. Every object of student will have its own name, year and batch. On a side note, static data members are shared among objects. All objects share codes of all methods. For example, every student object uses same logic to find out grades or any other method.
Which of the following is true about constructors. 1) They cannot be virtual. 2) They cannot be private. 3) They are automatically called by new operator. A-All 1, 2, and 3 B-Only 1 and 3 C-Only 1 and 2 D-Only 2 and 3
B-Only 1 and 3 1) True: Virtual constructors don't make sense, it is meaningless to the C++ compiler to create an object polymorphically. 2) False: Constructors can be private, for example, we make copy constructors private when we don't want to create copyable objects. The reason for not making copyable object could be to avoid shallow copy. 3) True: Constructors are automatically called by new operator, we can in-fact pass parameters to constructors.
#include<iostream> using namespace std; class Base { public: virtual void show() = 0; }; int main(void) { Base b; Base *bp; return 0; } Run on IDE A-There are compiler errors in lines "Base b;" and "Base bp;" B-There is compiler error in line "Base b;" C-There is compiler error in line "Base bp;" D-No compiler Error
B-There is compiler error in line "Base b;" Since Base has a pure virtual function, it becomes an abstract class and an instance of it cannot be created. So there is an error in line "Base b". Note that there is no error in line "Base *bp;". We can have pointers or references of abstract classes.
How to create a dynamic array of pointers (to integers) of size 10 using new in C++? Hint: We can create a non-dynamic array using int *arr[10] A-int *arr = new int *[10]; B-int **arr = new int *[10]; C-int *arr = new int [10]; D-Not Possible
B-int **arr = new int *[10];
Assume that an integer and a pointer each takes 4 bytes. Also, assume that there is no alignment in objects. Predict the output following program. #include<iostream> using namespace std; class Test { static int x; int *ptr; int y; }; int main() { Test t; cout << sizeof(t) << " "; cout << sizeof(Test *); } Run on IDE A 12 4 B 12 12 C 8 4 D 8 8
C 8 4 or a compiler where pointers take 4 bytes, the statement "sizeof(Test *)" returns 4 (size of the pointer ptr). The statement "sizeof(t)" returns 8. Since static is not associated with each object of the class, we get (8 not 12).
#include <iostream> using namespace std; int main() { try { throw 10; } catch (...) { cout << "default exception\n"; } catch (int param) { cout << "int exception\n"; } return 0; } A default exception B int exception C Compiler Error
C Compiler Error It is compiler error to put catch all block before any other catch. The catch(...) must be the last catch block.
Which of the following is true about the following program #include <iostream> class Test { public: int i; void get(); }; void Test::get() { std::cout << "Enter the value of i: "; std::cin >> i; } Test t; // Global object int main() { Test t; // local object t.get(); std::cout << "value of i in local t: "<<t.i<<'\n'; ::t.get(); std::cout << "value of i in global t: "<<::t.i<<'\n'; return 0; } Contributed by Pravasi Meet A Compiler Error: Cannot have two objects with same class name B Compiler Error in Line "::t.get();" C Compiles and runs fine
C Compiles and runs fine The above program compiles & runs fine. Like variables it is possible to create 2 objects having same name & in different scope.
#include <iostream> using namespace std; int main() { try { try { throw 20; } catch (int n) { cout << "Inner Catch\n"; throw; } } catch (int x) { cout << "Outer Catch\n"; } return 0; } A Outer Catch B Inner Catch C Inner Catch Outer Catch D Compiler Error
C Inner Catch Outer Catch The statement 'throw;' is used to re-throw an exception. This is useful when a function can handles some part of the exception handling and then delegates the remaining part to the caller. A catch block cleans up resources of its function, and then re throws the exception for handling elsewhere.
Predict the output of following C++ program. #include <iostream> using namespace std; class Test { static int x; public: Test() { x++; } static int getX() {return x;} }; int Test::x = 0; int main() { cout << Test::getX() << " "; Test t[5]; cout << Test::getX(); } A 0 0 B 5 5 C 0 5 D Compiler Error
C 0 5 - Correct Explanation: Static functions can be called without any object. So the call "Test::getX()" is fine. Since x is initialized as 0, the first call to getX() returns 0. Note the statement x++ in constructor. When an array of 5 objects is created, the constructor is called 5 times. So x is incremented to 5 before the next call to getX().
#include <iostream> using namespace std; template <typename T> T max(T x, T y) { return (x > y)? x : y; } int main() { cout << max(3, 7) << std::endl; cout << max(3.0, 7.0) << std::endl; cout << max(3, 7.0) << std::endl; return 0; } A 7 7.0 7.0 B Compiler Error in all cout statements as data type is not specified. C Compiler Error in last cout statement as call to max is ambiguous. D None of the above
C- Compiler Error in last cout statement as call to max is ambiguous.
#include <iostream> using namespace std; template <class T> class Test { private: T val; public: static int count; Test() { count++; } }; template<class T> int Test<T>::count = 0; int main() { Test<int> a; Test<int> b; Test<double> c; cout << Test<int>::count << endl; cout << Test<double>::count << endl; return 0; } A 0 0 B 1 1 C 2 1 D 1 0
C- 2 1 There are two classes created by the template: Test and Test. Since count is a static member, every class has its own copy of it. Also, count gets incremented in constructor.
What is the output of following program? #include <iostream> using namespace std; class Point { int x, y; public: Point(const Point &p) { x = p.x; y = p.y; } int getX() { return x; } int getY() { return y; } }; int main() { Point p1; Point p2 = p1; cout << "x = " << p2.getX() << " y = " << p2.getY(); return 0; } A- x = garbage value y = garbage value B- x = 0 y = 0 C- Compiler Error
C- Compiler Error Question 7 : There is compiler error in line "Point p1;". The class Point doesn't have a constructor without any parameter. If we write any constructor, then compiler doesn't create the default constructor. It is not true other way, i.e., if we write a default or parameterized constructor, then compiler creates a copy constructor.
Predict the output of following C++ program. #include<iostream> using namespace std; class Test { private: int x; public: Test(int x = 0) { this->x = x; } void change(Test *t) { this = t; } void print() { cout << "x = " << x << endl; } }; int main() { Test obj(5); Test *ptr = new Test (10); obj.change(ptr); obj.print(); return 0; } Run on IDE A x = 5 B x = 10 C Compiler Error D Runtime Error
C- Compiler Error this is a const pointer, so there is an error in line "this = t;"
Output? #include <iostream> using namespace std; template <int i> void fun() { i = 20; cout << i; } int main() { fun<10>(); return 0; } A 10 B 20 C Compiler Error
C- Compiler Error Compiler error in line "i = 20;" Non-type parameters must be const, so they cannot be modified.
Output of following C++ program? #include <iostream> class Test { public: void fun(); }; static void Test::fun() { std::cout<<"fun() is static\n"; } int main() { Test::fun(); return 0; } A-fun() is static B-Empty Screen C- Compiler Error
C- Compiler Error Explanation: The above program fails in compilation and shows below error messages. [Error] cannot declare member function 'void Test::fun()' to have static linkage [-fpermissive] In function 'int main()': [Error] cannot call member function 'void Test::fun()' without object If the static function is to be defined outside the class then static keyword must be present in function declaration only not in the definition outside the class. Following program is now correct. 1 #include class Test { public: static void fun(); }; void Test::fun() { std::cout<<"fun() is static\n"; } int main() { Test::fun(); return 0; }[/sourcecode]
#include<iostream> using namespace std; class Base {}; class Derived: public Base {}; int main() { Base *bp = new Derived; Derived *dp = new Base; } A-No Compiler Error B-Compiler Error in line "Base *bp = new Derived;" C- Compiler Error in line " Derived *dp = new Base;" D-Runtime Error
C- Compiler Error in line " Derived *dp = new Base;" A Base class pointer/reference can point/refer to a derived class object, but the other way is not possible.
#include<iostream> using namespace std; class Point { public: Point() { cout << "Constructor called"; } }; int main() { Point t1, *t2; return 0; } A-Compiler Error B- Constructor called Constructor called C- Constructor called
C- Constructor called onced Only one object t1 is constructed here. t2 is just a pointer variable, not an object
Predict output of the following program #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; } A-In Base In Base B-In Base In Derived C-In Derived In Derived D-In Derived In Base
C- In Derived In Derived Since show() is virtual in base class, it is called according to the type of object being referred or pointed, rather than the type of pointer or reference.
Which of the following operators should be preferred to overload as a global function rather than a member method? A-Postfix ++ B-Comparison Operator C-Insertion Operator << D-Prefix++
C- Insertion Operator cout is an object of ostream class which is a compiler defined class. When we do "cout << obj" where obj is an object of our class, the compiler first looks for an operator function in ostream, then it looks for a global function. One way to overload insertion operator is to modify ostream class which may not be a good idea. So we make a global method. Following is an example. #include <iostream> using namespace std; class Complex { private: int real; int imag; public: Complex(int r = 0, int i =0) { real = r; imag = i; } friend ostream & operator << (ostream &out, const Complex &c); }; ostream & operator << (ostream &out, const Complex &c) { out << c.real; out << "+i" << c.imag; return out; } int main() { Complex c1(10, 15); cout << c1; return 0; }
Which of the following operators are overloaded by default by the compiler? 1) Comparison Operator ( == ) 2) Assignment Operator ( = ) A -Both 1 and 2 B-Only 1 C-Only 2 D- None of the two
C- Only 2
Predict the output of following C++ program. #include<iostream> using namespace std; int &fun() { static int x = 10; return x; } int main() { fun() = 30; cout << fun(); return 0; } A-Compiler Error: Function cannot be used as lvalue B-10 C-30
C-30 When a function returns by reference, it can be used as lvalue. Since x is a static variable, it is shared among function calls and the initialization line "static int x = 10;" is executed only once. The function call fun() = 30, modifies x to 30. The next call "cout << fun()" returns the modified value.
In C++, const qualifier can be applied to 1) Member functions of a class 2) Function arguments 3) To a class data member which is declared as static 4) Reference variables A-Only 1, 2 and 3 B-Only 1, 2 and 4 C-All D-Only 1, 3 and 4
C-All When a function is declared as const, it cannot modify data members of its class. When we don't want to modify an argument and pass it as reference or pointer, we use const qualifier so that the argument is not accidentally modified in function. Class data members can be declared as both const and static for class wide constants. Reference variables can be const when they refer a const location.
#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; } A-Constructor Called. Before fun() called. After fun() called. B-Before fun() called. Constructor Called. Constructor Called. After fun() called. C-Before fun() called. Constructor Called. After fun() called. D-Constructor Called. Constructor Called. After fun() called.Before fun() called.
C-Before fun() called. Constructor called.After fun() called. Note that t is static in fun(), so constructor is called only once.
What should be put in a try block? 1. Statements that might cause exceptions 2. Statements that should be skipped in case of an exception A-Only 1 B-Only 2 C-Both 1 and 2
C-Both 1 and 2 The statements which may cause problems are put in try block. Also, the statements which should not be executed after a problem accursed, are put in try block. Note that once an exception is caught, the control goes to the next line after the catch block.
How can we restrict dynamic allocation of objects of a class using new? A-By overloading new operator B-By making an empty private new operator. C-By making an empty private new and new[] operators D-By overloading new operator and new[] operators
C-By making an empty private new and new[] operators If we declare new and [] new operators, then the objects cannot be created anywhere (within the class and outside the class) See the following example. We can not allocate an object of type Test using new. #include <stdlib.h> #include <stdio.h> #include <iostream> using namespace std; class Test { private: void* operator new(size_t size) {} void* operator new[](size_t size) {} }; int main() { Test *obj = new Test; Test *arr = new Test[10]; return 0; }
class Test { int x; }; int main() { Test t; cout << t.x; return 0; } A-0 B-Garbage Value C-Compiler Error
C-Compiler Error In C++, the default access is private. Since x is a private member of Test, it is compiler error to access it outside the class.
#include<iostream> using namespace std; class Test { public: Test(Test &t) { } Test() { } }; Test fun() { cout << "fun() Called\n"; Test t; return t; } int main() { Test t1; Test t2 = fun(); return 0; } A-fun() Called B-Empty Output C- Compiler Error: Because copy constructor argument is non-const
C-Compiler Error: Because copy constructor arguments is non-const
#include <iostream> using namespace std; class Test { public: Test() { cout << "Hello from Test() "; } } a; int main() { cout << "Main Started "; return 0; } A-Main Started B-Main Started Hello from Test() C-Hello from Test() Main Started D-Compiler Error: Global objects are not allowed
C-Hello from Test() Main Started Output is Hello from Test() Main Started There is a global object 'a' which is constructed before the main functions starts, so the constructor for a is called first, then main()' execution begins.
What happens when delete is used for a NULL pointer? int *ptr = NULL; delete ptr; A-Compiler Error B-Run-time Crash C-No Effect
C-No Effect Deleting a null pointer has no effect, so it is not necessary to check for a null pointer before calling delete.
Output of following program? #include <iostream> #include<string> using namespace std; class Base { public: virtual string print() const { return "This is Base class"; } }; class Derived : public Base { public: virtual string print() const { return "This is Derived class"; } }; void describe(Base p) { cout << p.print() << endl; } int main() { Base b; Derived d; describe(b); describe(d); return 0; } A-This is Derived class This is Base class B-This is Base class This is Derived class C-This is Base class This is Base class d-Compiler Error
C-This is Base class This is Base class Note that an object of Derived is passed in describe(d), but print of Base is called. The describe function accepts a parameter of Base type. This is a typical example of object slicing, when we assign an object of derived class to an object of base type, the derived class object is sliced off and all the data members inherited from base class are copied. Object slicing should be avoided as there may be surprising results like above. As a side note, object slicing is not possible in Java. In Java, every non-primitive variable is actually a reference.
Consider the pushdown automaton (PDA) below which runs over the input alphabet (a, b, c). It has the stack alphabet {Z0, X} where Z0 is the bottom-of-stack marker. The set of states of the PDA is (s, t, u, f} where s is the start state and f is the final state. The PDA accepts by final state. The transitions of the PDA given below are depicted in a standard manner. For example, the transition (s, b, X) → (t, XZ0) means that if the PDA is in state s and the symbol on the top of the stack is X, then it can read b from the input and move to state t after popping the top of stack and pushing the symbols Z0 and X (in that order) on the stack. (s, a, Z0) → (s, XXZ0) (s, ϵ, Z0) → (f, ϵ) (s, a, X) → (s, XXX) (s, b, X) → (t, ϵ) (t, b, X) → (t,.ϵ) (t, c, X) → (u, ϵ) (u, c, X) → (u, ϵ) (u, ϵ, Z0) → (f, ϵ) The language accepted by the PDA is A-{albmcn | l = m = n} B-{albmcn | l = m} C-{albmcn | 2l = m+n} D-{albmcn | m=n
C-{albmcn | 2l = m+n}
According to the C++11 standard, what is the output of this program? #include <iostream> void f(int) { std::cout << 1; } void f(unsigned) { std::cout << 2; } int main() { f(-2.5); }
Compilation Error This overload is ambiguous. Why? There are two viable functions for the call f(-2.5). For the compiler to select one, one of them needs to be better than the other, or the program is ill-formed. In our case, they are equally good, making the program ill-formed. According to §13.3.3 in the standard, a viable one-argument function is better than another if the conversion sequence for the argument is better. So why isn't the int conversion sequence better than the unsigned conversion sequence, given that the double is signed? All conversions are given a rank, and both "double => int" and "double => unsigned int" are of type "floating-integral conversion", which has rank "conversion". See Table 12 in the standard and §4.9. Since they have the same rank, no conversion is better than the other, and the program is ill-formed.
What gets printed by the code below? 01 #include <iostream> 02 03 class A 04 { 05 public: 06 void foo() const { std::cout << "A"; } 07 }; 08 09 class B 11 { 12 public: 13 void foo() const { std::cout << "B"; } 14 }; 15 16 class C : public A, public B 17 { 18 using A::foo; 19 }; 20 21 int main() 22 { 23 C c; 24 c.foo(); 25 return 0; 26 } A B AB Compiler error on line 24 Undefined behavior
Compiler error on line 24 - correct description: The accessibility property of the introduced foo method from the A type is private in the C type, hence it will not be publicly accessible. This is the case regardless of the fact that the A type is publicly derived and the foo method has public accessibility in A type. This is further explained in the C++ standard, section 7.3.3 pg 15 by the following: "The alias created by the using- declaration has the usual accessibility for a member-declaration." Submit Answer
Which of the following is NOT a character constant? (A) 'Thank You' (B) 'Enter values of P, N, R' (C) '23.56E-03' (D) All the above
D
#include<iostream> using namespace std; class Test { private: static int count; public: Test& fun(); }; int Test::count = 0; Test& Test::fun() { Test::count++; cout << Test::count << " "; return *this; } int main() { Test t; t.fun().fun().fun().fun(); return 0; } A-Compiler Error B-4 4 4 4 C-1 1 1 1 D- 1234
D- 1234 Static members are accessible in non-static functions, so no problem with accessing count in fun(). Also, note that fun() returns the same object by reference.
We must use initializer list in a constructor when A-There is a reference variable in class B-There is a constant variable in class C-There is an object of another class. And the other class doesn't have default constructor. D- All of the above
D- All of the above
Which of the following is true about virtual functions in C++. A-Virtual functions are functions that can be overridden in derived class with the same signature. B-Virtual functions enable run-time polymorphism in a inheritance hierarchy. C-If a function is 'virtual' in the base class, the most-derived class's implementation of the function is called according to the actual type of the object referred to, regardless of the declared type of the pointer or reference. In non-virtual functions, the functions are called according to the type of reference or pointer. D-All of the above
D- All of the above
What is the use of this pointer? A-When local variable's name is same as member's name, we can access member using this pointer. B-To return reference to the calling object C-Can be used for chained function calls on an object D-All of the above
D- All of the above See following example for first use. /* local variable is same as a member's name */ class Test { private: int x; public: void setX (int x) { // The 'this' pointer is used to retrieve the object's x // hidden by the local variable 'x' this->x = x; } void print() { cout << "x = " << x << endl; } }; And following example for second and third point. #include using namespace std; class Test { private: int x; int y; public: Test(int x = 0, int y = 0) { this->x = x; this->y = y; } Test &setX(int a) { x = a; return *this; } Test &setY(int b) { y = b; return *this; } void print() { cout << "x = " << x << " y = " << y << endl; } }; int main() { Test obj1(5, 5); // Chained function calls. All calls modify the same object // as the same object is returned by reference obj1.setX(10).setY(20); obj1.print(); return 0; }
Which of the followings is/are automatically added to every class, if we do not write our own. A-Copy Constructor B-Assignment Operator C-A constructor without any parameter D- All of the above
D- All of the above Explanation: In C++, if we do not write our own, then compiler automatically creates a default constructor, a copy constructor and a assignment operator for every class.
Predict the output of following C++ program #include<iostream> using namespace std; class Test { private: int x; int y; public: Test(int x = 0, int y = 0) { this->x = x; this->y = y; } static void fun1() { cout << "Inside fun1()"; } static void fun2() { cout << "Inside fun2()"; this->fun1(); } }; int main() { Test obj; obj.fun2(); return 0; } A Inside fun2() Inside fun1() B Inside fun2() C Inside fun1() Inside fun2() D Compiler Error
D- Compile Error There is error in fun2(). It is a static function and tries to access this pointer. this pointer is not available to static member functions as static member function can be called without any object.
Which of the following is FALSE about references in C++ A - References cannot be NULL B -A reference must be initialized when declared C -Once a reference is created, it cannot be later made to reference another object; it cannot be reset. D- References cannot refer to constant value
D- References cannot refer to constant value. We can create a constant reference that refers to a constant. For example, the following program compiles and runs fine. #include<iostream> using namespace std; int main() { const int x = 10; const int& ref = x; cout << ref; return 0; }
Which of the following is true? A Static methods cannot be overloaded. B Static data members can only be accessed by static methods. C- Non-static data members can be accessed by static methods. D- Static methods can only access static members (data and methods)
D- Static methods can only access static members (data and methods) -Correct
Which of the following is true about templates. 1) Template is a feature of C++ that allows us to write one code for different data types. 2) We can write one function that can be used for all data types including user defined types. Like sort(), max(), min(), ..etc. 3) We can write one class or struct that can be used for all data types including user defined types. Like Linked List, Stack, Queue ..etc. 4) Template is an example of compile time polymorphism. A-1 and 2 B-1, 2 and 3 C-1, 2 and 4 D-1, 2, 3 and 4
D-1,2,3 and 4
Which of the following is true about new when compared with malloc. 1) new is an operator, malloc is a function 2) new calls constructor, malloc doesn't 3) new returns appropriate pointer, malloc returns void * and pointer needs to typecast to appropriate type. A-1 and 3 B-2 and 3 C-1 and 2 D-All 1, 2 and 3
D-All 1, 2 and 3
#include<iostream> using namespace std; class A { public: A(){ cout <<"1";} A(const A &obj){ cout <<"2";} }; class B: virtual A { public: B(){cout <<"3";} B(const B & obj){cout<<"4";} }; class C: virtual A { public: C(){cout<<"5";} C(const C & obj){cout <<"6";} }; class D:B,C { public: D(){cout<<"7";} D(const D & obj){cout <<"8";} }; int main() { D d1; D d(d1); } Which of the below is not printed? A-2 B-4 C-6 D-All of the above
D-All of the above Output will be 13571358 as 1357 (for D d1) and as 1358 (for D d(d1))......reason is that ......during inheritance we need to explicitly call copy constructor of base class otherwise only default constructor of base class is called. One more thing, as we are using virtual before base class, there will be only one copy of base class in multiple inheritance. And without virtual output will be......13157....&...13158 as (1315713158) respectively for each derived class object.
#include<iostream> using namespace std; class Base { public: int fun() { cout << "Base::fun() called"; } int fun(int i) { cout << "Base::fun(int i) called"; } }; class Derived: public Base { public: int fun() { cout << "Derived::fun() called"; } }; int main() { Derived d; d.fun(5); return 0; } A-Base::fun(int i) called B-Derived::fun() called C-Base::fun() called D-Compiler Error
D-Compiler Error If a derived class writes its own method, then all functions of base class with same name become hidden, even if signatures of base class functions are different. In the above question, when fun() is rewritten in Derived, it hides both fun() and fun(int) of base class.
Predict the output of following program. #include <iostream> using namespace std; class Point { int x, y; public: Point(int i = 0, int j =0) { x = i; y = j; } int getX() const { return x; } int getY() {return y;} }; int main() { const Point t; cout << t.getX() << " "; cout << t.gety(); return 0; } A Garbage Values B-0 0 C-Compiler Error in line cout << t.getX() << " "; D-Compiler Error in line cout << t.gety();
D-Compiler Error in line cout << t.gety(); There is compiler Error in line cout << t.gety(); A const object can only call const functions.
Output of following program #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; } A-In Base In Base B-In Base In Derived C-In Derived In Derived D-In Derived In Base
D-In Derived In Base Explanation: Initially base pointer points to a derived class object. Later it points to base class object,
Which of the following concepts of OOPS means exposing only necessary information to client? 1. Data binding 2. Encapsulation 3. Abstraction 4. Data hiding
Data Hiding
malloc() vs new
Following are the differences between malloc() and operator new. 1) new calls constructors, while malloc() does not. In fact primitive data types (char, int, float.. etc) can also be initialized with new. For example, below program prints 10. #include<iostream> using namespace std; int main() { int *n = new int(10); // initialization with new() cout<<*n; getchar(); return 0; } 2) new is an operator, while malloc() is a function. 3) new returns exact data type, while malloc() returns void *.
When is a copy constructor called?
In C++, 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. 4. When compiler generates a temporary object. It is however, not guaranteed that a copy constructor will be called in all these cases, because the C++ Standard allows the compiler to optimize the copy away in certain cases, one example being the return value optimization (sometimes referred to as RVO).
According to the C++11 standard, what is the output of this program? #include <iostream> struct E { E() { std::cout << "1"; } E(const E&) { std::cout << "2"; } ~E() { std::cout << "3"; } }; E f() { return E(); } int main() { f(); }
In f(), an E object is constructed, and 1 is printed. This object is then returned to main(), and one could expect the copy constructor to be called, printing 2. However, §6.6.3¶2 in the standard says "Note: A copy or move operation associated with a return statement may be elided", meaning that the implementation is free to skip the copy constructor. This is optional, and unspecified behaviour. Most implementations will elide the copy constructor and output 13, but may be urged not to so with the -fno-elide-constructors option and output 1233. For more information about the return value optimisation, and an investigation of which implementations use it,
What is the output? #include <iostream> using namespace std; class A { int i; public: A(int ); }; A::A(int arg) { i = arg; cout << "A's Constructor called: Value of i: " << i << endl; } // Class B contains object of A class B { A a; public: B(int ); }; B::B(int x):a(x) { //Initializer list must be used cout << "B's Constructor called"; } int main() { B obj(10); return 0; }
OUTPUT: A's Constructor called: Value of i: 10 B's Constructor called For initialization of member objects which do not have default constructor: In the following example, an object "a" of class "A" is data member of class "B", and "A" doesn't have default constructor. Initializer List must be used to initialize "a". If class A had both default and parameterized constructors, then Initializer List is not must if we want to initialize "a" using default constructor, but it is must to initialize "a" using parameterized constructor.
What is the output? #include<iostream> using namespace std; class Test { const int t; public: Test(int t):t(t) {} //Initializer list must be used int getT() { return t; } }; int main() { Test t1(10); cout<<t1.getT(); return 0; }
Output - 10 For initialization of non-static const data members: const data members must be initialized using Initializer List. In the following example, "t" is a const data member of Test class and is initialized using Initializer List.
What is the output ? // Initialization of reference data members #include<iostream> using namespace std; class Test { int &t; public: Test(int &t):t(t) {} //Initializer list must be used int getT() { return t; } }; int main() { int x = 20; Test t1(x); cout<<t1.getT()<<endl; x = 30; cout<<t1.getT()<<endl; return 0; }
Output 20-30 For initialization of reference members: Reference members must be initialized using Initializer List. In the following example, "t" is a reference member of Test class and is initialized using Initializer List.
According to the C++11 standard, what is the output of this program? #include <iostream> template <class T> void f(T &i) { std::cout << 1; } template <> void f(const int &i) { std::cout << 2; } int main() { int i = 42; f(i); }
Output is "1". The templated function will be instantiated as void f(int&), which is a better match than f(const int&).
Predict the output of following program #include <iostream> using namespace std; int main() { const char* p = "12345"; const char **q = &p; *q = "abcde"; const char *s = ++p; p = "XYZWVU"; cout << *++s; return 0; } Run on IDE Compiler Error c C b D Garbage Value const keyword Discuss it
Output is 'c' const char* p = "12345″ declares a pointer to a constant. So we can't assign something else to *p, but we can assign new value to p. const char **q = &p; declares a pointer to a pointer. We can't assign something else to **q, but we can assign new values to q and *q. *q = "abcde"; changes p to point to "abcde" const char *s = ++p; assigns address of literal "bcde" to s. Again *s can't be assigned a new value, but s can be changed. The statement printf("%cn", *++s) changes s to "cde" and first character at s is printed.
What gets printed by this program? #include <iostream> struct Shape { void print() { std::cout << "SHAPE" << std::endl; } }; struct Box : public Shape { void print() { std::cout << "BOX" << std::endl; } }; int main(int argc, char** argv) { Shape* s1 = new Box; s1->print(); return 0; } SHAPE BOX undefined code is ill-formed unspecified
Shape-correct description: Shape::print is not a virtual function. Therefore Shape::print is called even though s1 points to a Box object. If print was virtual, then BOX would be printed.
The below is legal int x = 5; class x { }; int main(int argc, char** argv) { class x y; return 0; } TRUE OR FALSE
TRUE You can have a class and a regular variable with the same name. However the class name will been hidden and the elaborated-type-specfier must be used to access the class name.
True or false? Every expression is an lvalue or an rvalue? true false
TRUE- correct description: Its true, see Standard 3.10/1
Which of the following is true about this pointer? A.It is passed as a hidden argument to all function calls B.It is passed as a hidden argument to all non-static function calls C It is passed as a hidden argument to all static functions D None of the above
The 'this' pointer is passed as a hidden argument to all non-static member function calls and is available as a local variable within the body of all non-static functions. 'this' pointer is a constant pointer that holds the memory address of the current object. 'this' pointer is not available in static member functions as static member functions can be called without any object (with class name).
According to the C++11 standard, what is the output of this program? #include <iostream> class A { public: A() { std::cout << 'a'; } ~A() { std::cout << 'A'; } }; class B : public A { public: B() { std::cout << 'b'; } ~B() { std::cout << 'B'; } }; int main() { B b; }
The base class constructor is called before the inherited constructor. The inherited destructor is called before the base class destructor.
The code below is legal. True or false? #include <iostream> const char* Foo() { return "Hello World"; } int main() { const char* str = Foo(); std::cout << str << std::endl; return 0; } true or false
True - correct description: String literals have static storage duration, therefore they can be referenced anywhere in the translation unit, even though it is defined in a function
Given the code below what will be the output to stdout? #include <cstdio> 00 void foo(int v1, int v2, int v3, int v4) 01 { 02 printf("%d %d %d %d\n",v1,v2,v3,v4); 03 } 04 05 int main() 06 { 07 int lut[] = { 1, 2, 3, 4 }; 08 int idx = 0; 09 foo(lut[idx++],lut[idx++],lut[idx++],lut[idx++]); 10 return 0; 11 } 1 2 3 4 0 1 2 3 4 3 2 1 Compiler Error Undefined behavior
Undefined behavior - correct description: As per the standard section 5.4: "Except where noted, the order of evaluation of operands of individual operators and subexpressions of individual expressions, and the order in which side effects take place, is unspecified58) Between the previous and next sequence point a scalar object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be accessed only to determine the value to be stored. The requirements of this paragraph shall be met for each allowable ordering of the subexpressions of a full expression; otherwise the behavior is undefined."
Can destructors be virtual in C++? Yes No
YES
Can destructors be private in C++? Yes No
Yes Whenever we want to control destruction of objects of a class, we make the destructor private. For dynamically created objects, it may happen that you pass a pointer to the object to a function and the function deletes the object. If the object is referred after the function call, the reference will become dangling.
How does C++ compiler differs between overloaded postfix and prefix operators? A-C++ doesn't allow both operators to be overlaoded in a class B-A postfix ++ has a dummy parameter C-A prefix ++ has a dummy parameter D-By making prefix ++ as a global function and postfix as a member function.
class Complex { private: int real; int imag; public: Complex(int r, int i) { real = r; imag = i; } Complex operator ++(int); Complex & operator ++(); }; Complex &Complex::operator ++() { real++; imag++; return *this; } Complex Complex::operator ++(int i) { Complex c1(real, imag); real++; imag++; return c1; } int main() { Complex c1(10, 15); c1++; ++c1; return 0; }
What gets printed? #include <iostream> struct A { A() : val() {} A(int v) : val(v) {} A(A a) : val(a.val) {} int val; }; int main(int argc, char** argv) { A a1(5); A a2(a1); std::cout << a1.val + a2.val << std::endl; return 0; } 0 5 10 code is ill-formed unspecified
code is ill-formed description: It is illegal to have a constructor whose first and only non-default argument is a value parameter for the class type.
What gets printed? #include <iostream> struct mybase { int x; template <int RANGE> virtual void print() { std::cout << RANGE + x + 1 << std::endl; } }; struct myderived : public mybase { template <int RANGE> void print() { std::cout << RANGE + x + 2 << std::endl; } }; int main(int argc, char** argv) { mybase* b = new myderived; b->x = 1; b->print<5>(); return 0; } 2 6 7 8 code is ill-formed
code is ill-formed - correct description: A member function template can not be virtual.
What gets printed by this program? #include <iostream> struct Shape { virtual Shape* duplicate() { std::cout << "SHAPE" << std::endl; return new Shape; } virtual ~Shape() {} }; struct Box : public Shape { virtual Box* duplicate() { std::cout << "BOX" << std::endl; return new Box; } }; int main(int argc, char** argv) { Shape* s1 = new Box; Shape* s2 = s1->duplicate(); delete s1; delete s2; return 0; } SHAPE BOX undefined code is ill-formed unspecified
description: BOX is printed. The return type of an overriding virtual function must have either the same type as the function it is overriding or both functions must return a pointer or reference with the same cv-qualifications whereby the class pointed or reffered to in the overridden function is an unambiguous and accessible direct or indirect base class of the class pointed or referred to in the overriding function.
Which lines below are ill-formed? 1 #include <iostream> 2 3 struct A 4 { 5 A(int& var) : r(var) {} 6 7 int &r; 8 }; 9 10 int main(int argc, char** argv) 11 { 12 int x = 23; 13 14 A a1(x); 15 16 A a2 = a1; 17 18 a2 = a1; 19 20 return 0; 21 } 14 16 18 14, 16 16, 18
description: It is ill-formed to use an implicitly defined assignment operator when one of the members that will need to be copied is a reference. (Line 18)
Which lines below should not compile? 1 #include <iostream> 2 3 class Bar 4 { 5 protected: 6 static int x; 7 int y; 8 }; 9 10 int Bar::x = 33; 11 12 class Barrel : public Bar 13 { 14 public: 15 void foo(Bar* b, Barrel* d) 16 { 17 b->y = 0; 18 d->y = 0; 19 Bar::x = 0; 20 Barrel::x = 0; 21 } 22 }; 23 24 int main(int argc, char** argv) 25 { 26 Barrel b; 27 b.foo(&b, &b); 28 return 0; 29 } none 17 18 19 20
description: Line 17 should not compile. Access to non-static protected members of a base class can not be via a pointer or reference to the base class.
What gets printed by this program? #include <iostream> struct Shape { virtual void print() { std::cout << "SHAPE" << std::endl; } virtual ~Shape() {} }; struct Box : public Shape { virtual void print(int i) { std::cout << "BOX" << std::endl; } }; int main(int argc, char** argv) { Shape* s = new Box; s->print(); delete s; return 0; } SHAPE BOX undefined code is ill-formed unspecified
description: SHAPE is printed. A function with a different signature does not override a function in a base class even if the function name is the same.
Which of the following statements are true? 1) Conversion functions of class A convert from class A into another type 2) Conversion functions of class A are used to convert from another given type into class A 3) Converting constructors must be callable with a single argument 1 2 3 1 and 3 2 and 3
description: The 2nd statement is not true
What gets printed by this program? #include <iostream> struct Shape { virtual void print() { std::cout << "SHAPE" << std::endl; } virtual ~Shape() {} }; struct Box : public virtual Shape { void print() { std::cout << "BOX" << std::endl; } }; struct Sphere : public virtual Shape { void print() { std::cout << "SPHERE" << std::endl; } }; struct GeoDisc : public Box, public Sphere { }; int main(int argc, char** argv) { Shape* s = new GeoDisc; s->print(); delete s; return 0; } SHAPE BOX SPHERE undefined code is ill-formed
description: The code is ill-formed. Virtual functions must have a unique "final overrider" that overrides all other instances of that function in its inheritance heirarchy. In this case neither Box::print nor Sphere::print override each other, so the condition is not met and the GeoDisc class is ill-formed.
What gets printed by this program? #include <iostream> struct Shape { virtual Shape* duplicate() { return new Shape; } virtual void print() { std::cout << "SHAPE" << std::endl; } virtual ~Shape() {} }; struct Box : public Shape { virtual Box* duplicate() { return new Box; } virtual void print() { std::cout << "BOX" << std::endl; } }; int main(int argc, char** argv) { Shape* s1 = new Box; Box* b1 = s1->duplicate(); b1->print(); delete s1; delete b1; return 0; } SHAPE BOX undefined code is ill-formed unspecified
description: The program is ill-formed. The return type of the virtual function that is called dynamically is converted to the return type of the overridden function. In this case the result of the duplicate() function is a pointer to a Box object but converted to a Shape pointer. Therefore the assignment from the return value to b1 is ill-formed.
What gets printed? #include <iostream> struct A { A() : val(0) {} A(int v) : val(v) {} A(A& a) : val(a.val) {} int val; }; int main(int argc, char** argv) { const A a1; const A a2(5); const A a3 = a2; std::cout << a1.val + a2.val + a3.val << std::endl; return 0; } 0 5 10 code is ill-formed undefined
description: The program is ill-formed. The third line of main tries to initialize a3 with a2, but A's copy constructor takes a non-const reference which violates a2's const declaration.
What is the maximum number of implicitly defined constructors that this struct will have? struct A { A(A& a) { } A(double d) {} int val; }; 0 1 2 implementation specified undefined
description: There will be no implicity defined constructors for this struct.
Static member functions of classes can be virtual. True or false? true false
false description: Static member functions can not be virtual
A function call is always an rvalue. True or false? a- true b- false
false - correct description: A function call can be an lvalue if and only if the return value is a reference
In namespace foo, the function bar can access the variable x also declared in namespace foo? #include <iostream> namespace foo { void bar() { x++; } int x; } int main(int argc, char** argv) { return 0; } True OR False
false - correct description: Names used in a namespace must be declared before before their use
The code below would declare an array of references, if we had properly initalized the references. True or false? int main() { int& x[50]; return 0; } true false
false - correct description: There is no such thing as an array of references. Also there are no references to references or pointers to references.
The variable x is accesible in the else clause of this program? int main(int argc, char** argv) { if ( argc > 2 ) { int x = 5; } else { } return 0; } TRUE OR FALSE
false - correct description: Variables declared in blocks of if,else-if,else are local to the block they were declared in.
Which of the following functions are found when called in main during name lookup? #include <iostream> namespace standards { struct datastructure { }; void foo(const datastructure& ds) { } void bar() { } } int main(int argc, char** argv) { standards::datastructure ds; foo(ds); bar(); return 0; } a)foo b)bar c)foo and bar d)neither
foo - correct description: This is called koenig lookup or argument dependent name lookup. In this case, the namespace 'standards' is searched for a function 'foo' because its argument 'ds' is defined in that namespace. For function 'bar', no additional namespaces are searched and the name is not found. More details are in 3.4.2.
What value gets printed by the program? #include <iostream> int main() { int sum = 0; int array[3][] = {{0, 1, 2}, {3, 4, 5}, {6, 7, 8}}; for (int i = 0; i < 3 ; ++i) { for (int j = 2; j < 3 ; j++) { sum += array[i][j]; } } std::cout << sum << std::endl; return 0; } a- 9 b- 15 c- 21 d- ill-formed e- undefined
ill-formed - correct description: Only the first constant expression in a multiple dimension array can be ommitted. Therefore the declaration of the array in this example is ill-formed.
What is the output of the program? #include <iostream> struct Foo { Foo() {} void go() { std::cout << "Foo" << std::endl; } }; struct Bar : public Foo { Bar() {} void go() { std::cout << "Bar" << std::endl; } }; int main(int argc, char** argv) { Bar b; const Foo f = b; f.go(); return 0; } Foo Bar ill-formed undefined unspecified
ill-formed - correct description: The code is ill-formed. Non-const member functions can not be called on const objects.
What value gets printed by the program? #include <iostream> int foo(int x, int y = x) { return x+y+1; } int main(int argc, char** argv) { std::cout << foo(2) << std::endl; return 0; } a- 1 b- 3 c- 5 d- ill-formed e- undefined
ill-formed - correct description: The program is ill-formed. Parameters of a function can not be used in default argument expressions.
What value gets printed by the program? #include <iostream> int foo(int x, int y) { return x+y; } int foo(const int x, const int y) { return x+y+1; } int main(int argc, char** argv) { const int x = 3; const int y = 2; std::cout << foo(x,y) << std::endl; return 0; } a- 3 b- 5 c- 6 d- ill-formed e- undefined
ill-formed - correct description: There can only be one function with the same signature. Altering the cv qualification of parameters does not change the function signature. Therefore the two foo functions have the same signature and the program is ill-formed.
What value gets printed by the program? #include <iostream> int foo(int x, int y) { return x+y; } double foo(double x, double y) { return x+y; } int main(int argc, char** argv) { double (*ptr)(int, int); ptr = foo; std::cout << ptr(3,8) << std::endl; return 0; } a- 3 b- 8 c- 11 d- ill-formed e- undefined
ill-formed - correct description: The return type of a function does not alter the signature (for function overloading). However, the return type of a function DOES change the "type" of the function and thus the assignment of foo to ptr in not valid.
What is the value of x at the end of main? int main(int argc, char** argv) { int x = 50 % -7; return 0; } a- 1 b- -1 c- implementation defined d- undefined e- compiler error
implementation defined - correct description: if either operand to a modulus operator is negative the result is implementation defined
Given the code below, the variable y can be accessed in which blocks of code? 1 int main(int argc, char** argv) 2 { 3 4 if ( argc > 10 ) 5 { 6 7 } 8 else if (int y = argc - 1 ) 9 { 10 11 } 12 else 13 { 14 15 } 16 17 return 0; 18 }
lines 8-15 - correct description: The variable declared in the else-if did not exist before its declaration and can not be used after the end of the else clause. Variables declared in conditions of if,else-if,else structures can be used in all subsequent conditions and bodies of the if,else-if,else structure.
In addition to const_cast, which cast can be used to cast away constness? a- static_cast b- dynamic_cast c- reinterpret_cast d- none of the above
none of the above- correct description: Only const_cast (or c-style casts) can be used to cast away constness
What value gets printed by the program? #include <iostream> int main() { int x = 3; switch(x) { case 0: int x = 1; std::cout << x << std::endl; break; case 3: std::cout << x << std::endl; break; default: x = 2; std::cout << x << std::endl; } return 0; } a- 0 b -1 c - 2 d - 3 e - nothing, it is ill-formed
nothing, it is ill-formed - correct description: Jumping into a block and bypassing a declaration with an initialization is ill-formed. In this example there are cases which would bypass the declaration and initialization of block scope x declaration.
What value gets printed by the program? #include <iostream> struct Foo { Foo(int d) : x(d) {} int x; }; int main() { double x = 3.14; Foo f( int(x) ); std::cout << f.x << std::endl; return 0; } a- 0 b- 3 c- 3.14 d- nothing, its ill-formed e- implementation-defined
nothing, its ill-formed - correct description: Any construct that could possibly be considered a declaration is a declaration. In this example, the second line of main is interpreted as a function declaration in preference to an object declaration with initialization.
In addition to c-style, which casts can be used to cast an int to a pointer or a pointer to an int? a-static_cast b-dynamic_cast c-reinterpret_cast d-static_cast or dynamic_cast e-none of the above
reinterpret_cast- correct description: Only reinterpret_cast (or c-style casts) can be used to cast an int to a pointer or a pointer to an int
In addition to c-style, which casts can be used to cast an int into an enum? a- static_cast b-dynamic_cast c-reinterpret_cast d-static_cast or reinterpret_cast e-none of the above
static_cast- correct description: Only static_cast (or c-style casts) can be used to cast an int to an enum
What value does size print out? #include <iostream> const int SIZE = 5; struct tester { int array[SIZE]; enum { SIZE = 3 }; void size() { std::cout << sizeof(array) / sizeof(int); } }; int main(int argc, char** argv) { tester t; t.size(); return 0; }
undefined - correct description: 3.3.6/3 says if reordering member declarations in a class yields an alternate valid program the program is ill-formed. In this case the enum SIZE is not in scope when array is declared making the array size 5. However if the members were reordered to declare array after the definition of the enum the array size would be 3. Thus since reordering member declaration changes the program, it is undefined.
What is the value of the local variable x at the end of main? int x = 5; int main(int argc, char** argv) { int x = x; return 0; }
undefined - correct description: The local x in main hides the global x before the local x's initializer is considered. Therefore the local x is being initialized with itself (the local unitialized variable)
Given the assumptions in the comments, what values is printed for x? int main(int argc, char** argv) { // assume result printed is 4 std::cout << sizeof(int) << std::endl; int x = 0x1000; x = x << 32; std::cout << std::hex << x << std::endl; return 0; } a- 0x00000000 b- 0xFFFFFFFF c- implementation defined d- undefined
undefined - correct description: The result of a shift operation is undefined if the right operand is negative, or greater than or equal to the length in bits of the promoted left operand.
If assumptions in the code below are true what value would be the final value printed by this program? int main(int argc, char** argv) { // assume result printed is 4 std::cout << sizeof(int) << std::endl; int *x = new int; // assume result printed is 0x60000000 std::cout << x << std::endl; std::cout << x + 3 << std::endl; return 0; } a- 0x60000000 b- 0x60000003 c- 0x6000000C d- implementation defined e- undefined
undefined- correct description: In pointer addition and subtraction if both operands and the result do not point inside the same array (or 1 past the last element of the array) the result is undefined.
What is the output of the program? #include <iostream> struct BS { unsigned int color; }; struct car : public BS { }; struct truck : public BS { }; struct city : public car, public truck { }; int main(int argc, char** argv) { city c; c.color = 3; std::cout << c.color << std::endl; return 0; } 0 3 ill-formed undefined unspecified
unspecified - incorrect description: The code is ill-formed. The non-static members of a base class, that is an indirect or direct base class more than once, can not be referred to without qualification.
Of the variable definitions below, which ones have external linkage and can be accessed from another translation unit? int w = 1; static int x = 2; const int y = 3; extern const int z = 4; int main(int argc, char** argv) { return 0; } a- w, x, y and z b- w, y and z c- w and z d- y and z e- none
w and z - correct description: w has external linkage. x has internal linkage. y has internal linkage. z has external linkage
How many instances of an abstract class can be created? 1. 1 2. 5 3. 0 4. 13
zero
What value gets printed by the program? #include <iostream> int main(int argc, char** argv) { int x = 0; int y = 0; if (x++ && y++) { y += 2; } std::cout << x + y << std::endl; return 0; } a- 1 b- 2 c- 3 d- 4 e- undefined
1-correct description: If the first operand to the logical AND operator evaluates to false the second operand is guaranteed not to evaluate. Note: the logical OR operator is guaranteed not to evaluate the second operand if the first operand is true. Note: for the logical AND and OR operators, all side effects of the first expression, except for destruction of temporaries, happen before the second expression is evaluated.
Which of the following lines should NOT compile? 1 2 int main() 3 { 4 int a[54] = {}; 5 6 int b[54] = {}; 7 8 int* x = a; 9 10 int* const y = a; 11 12 b = x; 13 14 b = y; 15 16 return 0; 17 } a- 8, 10, 12, 14 b- 8, 12 c- 12, 14 d- none
12, 14 - correct description: Arrays can be implicity converted to pointers without casting -- 4.2. There is no implicit conversion from pointers to arrays.
What value for y gets printed in the program below? #include <iostream> const int x = 12; int main(int argc, char** argv) { enum dog { x = x, y }; std::cout << y << std::endl; return 0; }
13- correct description: An Enumeration's point of declaration is after its definition (which includes the initialization). Therefore in this case the value of the enum 'x' is initialized with the global 'x' which equals 12.
Which lines of code below should not compile? 1 struct Foo 2 { 3 }; 4 5 struct Bar 6 { 7 }; 8 9 10 int main() 11 { 12 Foo* f = new Foo; 13 14 Bar* b1 = f; 15 Bar* b2 = static_cast<Bar*>(f); 16 Bar* b3 = dynamic_cast<Bar*>(f); 17 Bar* b4 = reinterpret_cast<Bar*>(f); 18 Bar* b5 = const_cast<Bar*>(f); 19 20 return 0; 21 } a- 14 b- 14,15,18 c- 14,17,18 d- 14,15,17,18 e- 14,15,16,18
14,15,16,18 - correct description: Only reinterpret_cast can be used to convert a pointer to an object to a pointer to an unrelated object type. The dynamic cast would fail at run-time, however on most compilers it will also fail to compile because there are no virtual functions in the class of the pointer being casted.
Which lines of code below should cause the program to be undefined? 1 struct Foo 2 { 3 virtual ~Foo() {} 4 }; 5 6 struct Bar : public Foo 7 { 8 }; 9 10 int main(int argc, char** argv) 11 { 12 Foo* f = new Bar; 13 delete f; 14 f = 0; 15 delete f; 16 17 Foo* fa = new Bar[10]; 18 delete [] fa; 19 fa = 0; 20 delete fa; 21 22 return 0; 23 } a-none b-13 c-15 d-18 e-20
18- correct description: deleting NULL pointers have no effect. deleting a pointer to a base class which points to a derived object is legal assuming the base destructor is virtual. deleting an array of objects using a base class pointer is undefined.
What value gets printed by the program? #include <iostream> struct Foo { int x; operator int() { return 21; } }; int main(int argc, char** argv) { Foo f; f.x = 11; std::cout << (0?3:f) << std::endl; return 0; } a- 0 b- 3 c- 11 d- 21 e- undefined
21- correct description: The 2nd and 3rd operands to the conditional operator must be of the same type. If one of the two can be converted to the other, the conversion will occur. Note: if a conversion exists for each of the operands into the other's type, the program is ill-formed.
What value does foo print out? #include <iostream> const int SIZE = 5; struct tester { void foo() { std::cout << SIZE << std::endl; } enum { SIZE = 3 }; }; int main(int argc, char** argv) { tester t; t.foo(); return 0; }
3- correct description: Names defined at any point in a class are in scope in all member functions of the class. Thus the enum SIZE is in scope in the function foo and hides the global variable SIZE.
What is the value of y at the end of main? const int x = 5; int main(int argc, char** argv) { int x[x]; int y = sizeof(x) / sizeof(int); return 0; }
5 - correct The local x does not hide the global x until the end of the declaration. A local name will hide a global after the end of the declaration but before the beginning of initialization.
Which of the following lines should NOT compile? 1 int main() 2 { 3 int a = 2; 4 5 int* b = &a; 6 7 int const* c = b; 8 9 b = c; 10 11 return 0; 12 } a- 7 and 9 b- 7 c- 9 d- none
9 - correct description: int* can be implicity converted to int const* -- 4.4. There is no implicit conversion from int const* to int*.
According to the C++11 standard, what is the output of this program? #include<iostream> int main(){ int x=0; //What is wrong here??/ x=1; std::cout<<x; }
??/ is a trigraph. According to §2.4¶1, this trigraph is translated to \ before any other processing takes place. Since that \ is followed by a newline, the line x=1 is treated as a continuation of the comment. Note: Trigraphs will be removed from the standard in C++17.
According to the C++11 standard, what is the output of this program? #include <iostream> #include <vector> int main() { std::vector<int> v1(1, 2); std::vector<int> v2{ 1, 2 }; std::cout << v1.size() << v2.size(); }
ANSWER 12 To answer this we need to look at overload resolution of vector's constructors: §23.3.6.2¶3 says (somewhat redacted): vector(size_type n, const T& value); Effects: Constructs a vector with n copies of value So v1 contains one "2". §13.3.1.7 says (in summary) that when non-aggregate classes (such as vector) are list-initialized† and have an initializer list constructor (again, like vector), that constructor is chosen, and the argument list consists of the initializer list as a single argument. (†: 8.5.4¶1: List-initialization is initialization of an object or reference from a braced-init-list.) So v2 is initialized from the elements (aka initializer-clauses) in the braced-init-list, and contains the elements "1" and "2".
According to the C++11 standard, what is the output of this program? #include<iostream> int foo() { return 10; } struct foobar { static int x; static int foo() { return 11; } }; int foobar::x = foo(); int main() { std::cout << foobar::x; }
ANSWER 11 §3.4¶14 states ""if a variable member of a namespace is defined outside of the scope of its namespace then any name that appears in the definition of the member after the declarator-id) is looked up as if the definition of the member occurred in its namespace..." Using the class scope to specify the static member x changes the initial lookup-path for foo(). The scope at which x exists(that is, the enclosing namepsace where x was declared) is first searched before considering the surrounding namespaces.
According to the C++11 standard, what is the output of this program? #include <iostream> class A; class B { B() { std::cout << "B"; } public: friend B A::createB(); }; class A { public: A() { std::cout << "A"; } B createB() { return B(); } }; int main() { A a; B b = a.createB(); }
Answer This question The program has a compilation error. Explanation There is a compilation error when attempting to declare A::createB() a friend of B. To declare A::createB() a friend of B, the compiler needs to know that that function exists. Since it has only seen the declaration of A so far, not the full definition, it cannot know this.
#include <iostream> struct A { virtual std::ostream &put(std::ostream &o) const { return o << 'A'; } }; struct B : A { virtual std::ostream &put(std::ostream &o) const { return o << 'B'; } }; std::ostream &operator<<(std::ostream &o, const A &a) { return a.put(o); } int main() { B b; std::cout << b; }
Answer This question The program is guaranteed to output:. B This is a way to get polymorphic behaviour for operator <<
According to the C++11 standard, what is the output of this program? #include <iostream> int a; int main () { std::cout << a; }
Answer This question The program is guaranteed to output:. Its output is "0". Explanation Since a has static storage duration and no initializer, it is guaranteed to be zero-initialized. Had a been defined as a local non-static variable inside main(), this would not have happened. Note: int a has static storage duration because it is declared at namespace scope. It does not need to have static in front of it, that would only denote internal linkage.
According to the C++11 standard, what is the output of this program? #include <iostream> #include <type_traits> int main() { if(std::is_signed<char>::value){ std::cout << std::is_same<char, signed char>::value; }else{ std::cout << std::is_same<char, unsigned char>::value; } }
Answer This question The program is guaranteed to output:. Its output is "0". Explanation §3.9.1¶1 Plain char, signed char, and unsigned char are three distinct types
According to the C++11 standard, what is the output of this program? #include <iostream> #include <type_traits> using namespace std; int main() { int i, &j = i; [=] { cout << is_same<decltype ((j)), int >::value << is_same<decltype (((j))), int & >::value << is_same<decltype ((((j)))), int const& >::value << is_same<decltype (((((j))))), int && >::value << is_same<decltype((((((j)))))), int const&& >::value; }(); }
Answer This question The program is guaranteed to output:. Its output is "00100". Explanation §5.1.2¶18 says Every occurrence of decltype((x)) where x is a possibly parenthesized id-expression that names an entity of automatic storage duration is treated as if x were transformed into an access to a corresponding data member of the closure type that would have been declared if x were an odr-use of the denoted entity. So additional parentheses, as the in the code snippet above, are ignored. The member of the closure type corresponding to the as-if-captured j will be not a reference, but will have the referenced type of the reference, since it is captured by copy (§5.1.2¶14). Since the lambda is not declared mutable, the overloaded operator() of the closure type will be a const member function. 5.1.2¶5: "The closure type for a lambda-expression has a public inline function call operator (...) This function call operator is declared const if and only if the lambda-expression's parameter-declaration-clause is not followed by mutable." Since the expression for decltype is a parenthesized lvalue expression, §7.1.6.2¶4 has this to say: "The type denoted by decltype(e) is (...) T&, where T is the type of e;" As the expression occurs inside a const member function, the expression is const, and decltype((j)) denotes int const&. See also the example in §5.1.2¶18.
According to the C++11 standard, what is the output of this program? #include <iostream> #include <limits> int main() { int N[] = {0,0,0}; if ( std::numeric_limits<long int>::digits==63 and std::numeric_limits<int>::digits==31 and std::numeric_limits<unsigned int>::digits==32 ) { for (long int i = -0xffffffff; i ; --i) { N[i] = 1; } } else { N[1]=1; } std::cout << N[0] <<N [1] << N[2]; }
Answer This question The program is guaranteed to output:. Its output is "010". Explanation As the else part of the branch is obvious, we concentrate on the if part and make the assumptions present in the condition. §2.14.2 in the standard: "The type of an integer literal is the first of the corresponding list in Table 6." [Table 6: int, unsigned int, long int, unsigned long int ... for hexadecimal literals --end Table] in which its value can be represented." Since the literal 0xffffffff needs 32 digits, it can be represented as an unsigned int but not as a signed int, and is of type unsigned int. But what happens with the negative of an unsigned integer? §5.3.1 in the standard: "The negative of an unsigned quantity is computed by subtracting its value from 2^n , where n is the number of bits in the promoted operand." Here n is 32, and we get: 2^32 - 0xffffffff = 4294967296 - 4294967295 = 1 So i is initialised to 1, and N[1] is the only element accessed in the loop. (The second time around the loop, i is 0, which evaluates to false, and the loop terminates.)
According to the C++11 standard, what is the output of this program? #include <iostream> #include <utility> int y(int &) { return 1; } int y(int &&) { return 2; } template <class T> int f(T &&x) { return y(x); } template <class T> int g(T &&x) { return y(std::move(x)); } template <class T> int h(T &&x) { return y(std::forward<T>(x)); } int main() { int i = 10; std::cout << f(i) << f(20); std::cout << g(i) << g(20); std::cout << h(i) << h(20); return 0; }
Answer This question The program is guaranteed to output:. Its output is "112212". Explanation The T&& in the the templated functions do not necessarily denote an rvalue reference, it depends on the type that is used to instantiate the template. If instantiated with an lvalue, it collapses to an lvalue reference, if instantiated with an rvalue, it collapses to an rvalue reference. See note [1]. In this example, all three functions are called once with an lvalue and once with an rvalue. In all cases, calling with an lvalue (i) collapses T&& x to T& x (an lvalue reference), and calling with an rvalue (20) collapses T&& x to T&& x (an rvalue reference). Inside the functions, x itself is always an lvalue, no matter if its type is an rvalue reference or an lvalue reference. -For the first example, y(int&) is called for both cases. Output: 11. -For the second example, move(x) obtains an rvalue reference, and y(int&&)is called for both cases. Output: 22. -For the third example, forward<T>(x) obtains an lvalue reference when x is an lvalue reference, and an rvalue reference when x is an rvalue reference, resulting in first a call to y(int&)and then a call to y(int&&). Output: 12. Note [1]: §8.3.2¶6 in the standard: "If a (...) type template-parameter (§14.3.1) (...) denotes a type TR that is a reference to a type T, an attempt to create the type "lvalue reference to cv TR" creates the type "lvalue reference to T", while an attempt to create the type "rvalue reference to cv TR" creates the type TR." The example at the end of that paragraph is is worth a look. Note from the contributor: This demonstrates Scott Meyers's advice that use std::forward for universal references, and std::move for rvalue references.
According to the C++11 standard, what is the output of this program? #include <initializer_list> #include <iostream> struct A { A() { std::cout << "1"; } A(int) { std::cout << "2"; } A(std::initializer_list<int>) { std::cout << "3"; } }; int main(int argc, char *argv[]) { A a1; A a2{}; A a3{ 1 }; A a4{ 1, 2 }; }
Answer This question The program is guaranteed to output:. Its output is "1133". Explanation According to §8.5.4.3 in the C++ standard: "List-initialization of an object or reference of type T is defined as follows: — If the initializer list has no elements and T is a class type with a default constructor, the object is value-initialized. — Otherwise, if T is an aggregate, aggregate initialization is performed (§8.5.1). — Otherwise, if T is a specialization of std::initializer_list<E>, an initializer_list object is constructed as described below and used to initialize the object according to the rules for initialization of an object from a class of the same type (§8.5). — Otherwise, if T is a class type, constructors are considered. The applicable constructors are enumerated and the best one is chosen through overload resolution (§13.3, §13.3.1.7). If a narrowing conversion (see below) is required to convert any of the arguments, the program is ill-formed. — (more cases...)" a1 is default initialized, as described in §8.5.0.11 a2 doesn't actually use the initializer_list constructor with a list of zero elements, but the default constructor, as described by the first option of the list above. a3's and a4's constructor is chosen in overload resolution, as described in §13.3.1.7: "When objects of non-aggregate class type T are list-initialized (§8.5.4), overload resolution selects the constructor in two phases: — Initially, the candidate functions are the initializer-list constructors (§8.5.4) of the class T and the argument list consists of the initializer list as a single argument. — If no viable initializer-list constructor is found, overload resolution is performed again, where the candidate functions are all the constructors of the class T and the argument list consists of the elements of the initializer list." Initializer list constructors are greedy, so even though A(int) constructor is available, the standard mandates that initializer_list<int> is prioritized, and if - and only if - it's not available, the compiler is allowed to look for other constructors. (This is why it is not recommended to provide a constructor that ambiguously overloads with an initializer_list constructor. See the answer to #4 in http://herbsutter.com/2013/05/09/gotw-1-solution/ )
According to the C++11 standard, what is the output of this program? #include <iostream> #include <vector> int main() { std::vector<int> v1(1, 2); std::vector<int> v2{ 1, 2 }; std::cout << v1.size() << v2.size(); }
Answer This question The program is guaranteed to output:. Its output is "12". Explanation To answer this we need to look at overload resolution of vector's constructors: §23.3.6.2¶3 says (somewhat redacted): vector(size_type n, const T& value); Effects: Constructs a vector with n copies of value So v1 contains one "2". §13.3.1.7 says (in summary) that when non-aggregate classes (such as vector) are list-initialized† and have an initializer list constructor (again, like vector), that constructor is chosen, and the argument list consists of the initializer list as a single argument. (†: 8.5.4¶1: List-initialization is initialization of an object or reference from a braced-init-list.) So v2 is initialized from the elements (aka initializer-clauses) in the braced-init-list, and contains the elements "1" and "2".
According to the C++11 standard, what is the output of this program? #include <iostream> class C { public: C(int i) : i(i) { std::cout << i; } ~C() { std::cout << i + 5; } private: int i; }; int main() { const C &c = C(1); C(2); }
Answer This question The program is guaranteed to output:. Its output is "1276". Explanation §12.2¶3 in the standard: "Temporary objects are destroyed as the last step in evaluating the full-expression (...) that (lexically) contains the point where they were created." This means that normally the temporaries returned from C(1) and C(2) should be destroyed at the end of the line. However: §12.2¶5 states: "(...)when a reference is bound to a temporary. The temporary to which the reference is bound (...) persists for the lifetime of the reference", so the lifetime of the temporary returned by C(1) is extended to the end of main(). The temporary returned by C(2) is still destroyed at the end of the line, so it gets destroyed before the one returned by C(1).
According to the C++11 standard, what is the output of this program? #include <iostream> int main() { int a = 10; int b = 20; int x; x = (a, b); std::cout << x; }
Answer This question The program is guaranteed to output:. Its output is "20". Explanation The comma operator is applied on two expressions: a and b. According to §5.18¶10 in the standard: "A pair of expressions separated by a comma is evaluated left-to-right; the left expression is a discarded-value expression (...) The type and value of the result are the type and value of the right operand" The right operand here being b, with the value 20. This is then the resulting value of the expression (a, b), and 20 is assigned to x.
According to the C++11 standard, what is the output of this program? #include <iostream> template <template <typename> class> struct X { X() { std::cout << "1"; } }; template <typename> struct Y {}; template <typename T> using Z = Y<T>; template <> struct X<Y> { X() { std::cout << "2"; } }; int main() { X<Y> x1; X<Z> x2; }
Answer This question The program is guaranteed to output:. Its output is "21". Explanation X takes a template template parameter[1], meaning that any template argument for X needs to itself take a template parameter. For instance, you cannot do X<int>, but you can do X<Y>, since Y itself is a template. There are two definitions of X, first the general template one, then the specialization X<Y>. Y is a normal template. Z is a template alias declaration, meaning that Z is now an alias for Y (think of template aliases as a "typedef for templates"). Now let's look at main(): Defining a variable of type X<Y> uses that specialization (printing 2). But what happens when we use a template alias, as in X<Z>? Is the specialization X<Y> still used, since Z is an alias for Y? No. According to §14.5.7¶1 in the standard, a template alias declaration resolve to a new family of types. The specialization cannot be used, and the first template delcaration is used instead, printing 1. [1]: For a good introduction to template template parameters, see http://www.informit.com/articles/article.aspx?p=376878
According to the C++11 standard, what is the output of this program? #include <iostream> #include <string> void f(const std::string &) { std::cout << 1; } void f(const void *) { std::cout << 2; } int main() { f("foo"); const char *bar = "bar"; f(bar); }
Answer This question The program is guaranteed to output:. Its output is "22". Explanation A string literal is not a std::string, but a const char[] . If the compiler was to choose f(const std::string&), it would have to go through a user defined conversion and create a temporary std::string. Instead, it prefers f(const void*), which requires no user defined conversion.
According to the C++11 standard, what is the output of this program? #include <iostream> int f(int &a, int &b) { a = 3; b = 4; return a + b; } int main() { int a = 1; int b = 2; int c = f(a, a); std::cout << a << b << c; }
Answer This question The program is guaranteed to output:. Its output is "428". Explanation When f() is called with a as both parameters, both arguments refer to the same variable. This is known as aliasing. First, a is set to 3, then a is set to 4, then 4+4 is returned. b is never modified.
According to the C++11 standard, what is the output of this program? #include <iostream> class A { public: virtual void f() { std::cout << "A"; } }; class B : public A { public: void f() { std::cout << "B"; } }; void g(A a) { a.f(); } int main() { B b; g(b); }
Answer This question The program is guaranteed to output:. Its output is "A". Explanation g(A a) takes an object of type A by value, not by reference or pointer. This means that A's copy constructor is called on the object passed to g() (no matter if the object we passed was of type B), and we get a brand new object of type A inside g(). This is commonly referred to as slicing.
According to the C++11 standard, what is the output of this program? #include <iostream> #include <memory> #include <vector> class C { public: void foo() { std::cout << "A"; } void foo() const { std::cout << "B"; } }; struct S { std::vector<C> v; std::unique_ptr<C> u; C *const p; S() : v(1) , u(new C()) , p(u.get()) {} }; int main() { S s; const S &r = s; s.v[0].foo(); s.u->foo(); s.p->foo(); r.v[0].foo(); r.u->foo(); r.p->foo(); }
Answer This question The program is guaranteed to output:. Its output is "AAABAA". Explanation According to §8.3.1.1 in the C++ Standard, "The cv-qualifiers [e.g., const] apply to the pointer and not to the object pointed to." That is, const-ness is shallow with regards to raw pointers and references (and standard types that seek to emulate them, like std::unique_ptr) but not with regard to standard containers such as std::vector. In the code above, the object s is non-const, and so its members all retain their default const-ness and all calls through them invoke the non-const version of C::foo(). However, r refers to its object as a const instance of S. That const-ness changes the behavior of its member v, an std::vector which is "const-correct" in the sense that its operator[] returns const C& (see §23.2.3.16) and therefore invokes the const version of C::foo(). The const-ness of r's referent is also propagated to its members u and p (meaning one could not perform a mutating operation on u, e.g., calling r.u.reset()), but this has no effect on the instance of C that they both point *to*. That is, the pointers themselves become const, but the pointed-to objects remain non-const. Hence, they both still call the non-const version of C::foo(). The const-ness of the member S::p is the same for both s and r. Because it is declared as a const pointer, it does not change const-ness to follow the const-ness of its instance of S but remains a const pointer to a non-const object.
According to the C++11 standard, what is the output of this program? #include <iostream> struct A { A() { std::cout << "A"; } A(const A &a) { std::cout << "B"; } virtual void f() { std::cout << "C"; } }; int main() { A a[2]; for (auto x : a) { x.f(); } }
Answer This question The program is guaranteed to output:. Its output is "AABCBC". Explanation When the array is initialized, the default constructor is called once for each of the two objects in it. Then we iterate over the array using auto, which in our case is deduced to be A. This means the copy constructor will be called before f() for each iteration, printing BCBC. (Just as if we had written for (A x: a). If we want to avoid the copy constructor, we can write for (auto& x : a) instead. Then the loop would print CC. (Just as if we had written for (A& x: a).
According to the C++11 standard, what is the output of this program? #include <iostream> using namespace std; class A { public: A() { cout << "A"; } A(const A &) { cout << "a"; } }; class B: virtual A { public: B() { cout << "B"; } B(const B &) { cout<< "b"; } }; class C: virtual A { public: C() { cout<< "C"; } C(const C &) { cout << "c"; } }; class D:B,C { public: D() { cout<< "D"; } D(const D &) { cout << "d"; } }; int main() { D d1; D d2(d1); }
Answer This question The program is guaranteed to output:. Its output is "ABCDABCd". Explanation On the first line of main(), d1 is initialized, in the order A, B, C, D. That order is defined by §12.6.2¶10: " — First, and only for the constructor of the most derived class (1.8), virtual base classes are initialized in the order they appear on a depth-first left-to-right traversal of the directed acyclic graph of base classes, where "left-to-right" is the order of appearance of the base classes in the derived class base-specifier-list. — Then, direct base classes are initialized in declaration order as they appear in the base-specifier-list (...) — Finally, the compound-statement of the constructor body is executed. " So the output is ABCD. On the second line, d2 is initialized. But why are the constructors (as opposed to the copy constructors) for the base classes, called? Why do we see ABCd instead of abcd? As it turns out, an implicitly-defined copy constructor would have called the copy constructor of its bases (§12.8¶.15: "The implicitly-defined copy/move constructor for a non-union class X performs a memberwise copy/move of its bases and members."). But when you provide a user-defined copy constructor, this is something you have to do explicitly.
According to the C++11 standard, what is the output of this program? #include <iostream> class A { public: virtual void f() { std::cout << "A"; } }; class B : public A { private: void f() { std::cout << "B"; } }; void g(A &a) { a.f(); } int main() { B b; g(b); }
Answer This question The program is guaranteed to output:. Its output is "B". Explanation The "trick" here is that B::f() is called even though it is private. As §11.5.2 in the standard puts it: "Access is checked at the call point using the type of the expression used to denote the object for which the member function is called". The call point here being a.f(), and the type of the expression is A&.
According to the C++11 standard, what is the output of this program? #include <iostream> using namespace std; template<typename T> void adl(T) { cout << "T"; } struct S { }; template<typename T> void call_adl(T t) { adl(S()); adl(t); } void adl(S) { cout << "S"; } int main () { call_adl(S()); }
Answer This question The program is guaranteed to output:. Its output is "TS". Explanation §14.6¶9 states: "When looking for the declaration of a name used in a template definition, the usual lookup rules (§3.4.1, §3.4.2) are used for non-dependent names. The lookup of names dependent on the template parameters is postponed until the actual template argument is known (§14.6.2)." The first call to adl is a non-dependent call, so it is looked up at the time of definition of the function template. The resolution of the second call is deferred until the template is instantiated because it depends on a template parameter. template<typename T> void call_adl_function(T t) { adl(S()); // Independent, looks up adl now. adl(t); // Dependent, looks up adl later. } When adl is being looked up at the time of definition of the function template, the only version of adl that exists is the templated adl(T). Specifically, adl(S) does not exist yet, and is not a candidate. Note: At the time of writing, this program does not confirm to the standard in some recent versions of Visual Studio's C++ compiler.
According to the C++11 standard, what is the output of this program? #include <iostream> struct X { X() { std::cout << "a"; } X(const X &x) { std::cout << "b"; } const X &operator=(const X &x) { std::cout << "c"; return *this; } }; int main() { X x; X y(x); X z = y; z = x; }
Answer This question The program is guaranteed to output:. Its output is "abbc". Explanation The first line in main(), X x; is straightforward, it calls the default constructor. The next two lines is the heart of the question: The difference between X y(x) and X z = y is not that the first calls the copy constructor, and the second calls the copy assignment operator. The difference is that the first is direct initialization (§8.5.15 in the standard) and the second is copy initialization (§8.5.14). §8.5.16 says: "If the initialization is direct-initialization, or if it is copy-initialization where the (...) source type is the same class as (...) the class of the destination, constructors are considered." So both our cases use the copy constructor. Not until z = x; do we have an actual assignment that uses the assignment operator. See http://stackoverflow.com/questions/1051379/is-there-a-difference-in-c-between-copy-initialization-and-direct-initializati/1051468#1051468 for a more detailed discussion of direct vs. copy initialization.
According to the C++11 standard, what is the output of this program? #include <iostream> class A { public: A() { std::cout << "a"; } ~A() { std::cout << "A"; } }; class B { public: B() { std::cout << "b"; } ~B() { std::cout << "B"; } }; class C { public: C() { std::cout << "c"; } ~C() { std::cout << "C"; } }; A a; void foo() { static C c; } int main() { B b; foo(); }
Answer This question The program is guaranteed to output:. Its output is "abcBCA". Explanation §3.6.2¶4 in the standard: "It is implementation-defined whether the dynamic initialization of a non-local variable with static storage duration is done before the first statement of main. If the initialization is deferred to some point in time after the first statement of main, it shall occur before the first odr-use (3.2) of any function or variable defined in the same translation unit as the variable to be initialized." Since A() is not constexpr, the initialization of a is dynamic. There are two possibilities: - a is initialized before main() is called, i.e. before b is initialized. - a is not initialized before main(). It is however guaranteed to be initialized before the the use of any function defined in the same translation unit, i.e. before the constructor of b is called. When execution reaches B b, it is initialized as normal. Static local variables are initialized the first time control passes through their declaration, so c is initialized next. As main() is exited, its local variable b goes out of scope, and is destroyed. Finally, all static variables are destroyed in reverse order of their initialization, first c, then a.
According to the C++11 standard, what is the output of this program? #include <iostream> class A { public: A() { std::cout << "a"; } ~A() { std::cout << "A"; } }; class B { public: B() { std::cout << "b"; } ~B() { std::cout << "B"; } }; class C { public: C() { std::cout << "c"; } ~C() { std::cout << "C"; } }; A a; int main() { C c; B b; }
Answer This question The program is guaranteed to output:. Its output is "acbBCA". Explanation §3.6.2¶4 in the standard: "It is implementation-defined whether the dynamic initialization of a non-local variable with static storage duration is done before the first statement of main. If the initialization is deferred to some point in time after the first statement of main, it shall occur before the first odr-use (3.2) of any function or variable defined in the same translation unit as the variable to be initialized." Since A() is not constexpr, the initialization of a is dynamic. There are two possibilities: - a is initialized before main() is called, i.e. before b or c are initialized. - a is not initialized before main(). It is however guaranteed to be initialized before the the use of any function defined in the same translation unit, i.e. before the constructors of b and c are called. Then, b and c are initialized in order. Before main() exits, b and c are destructed in the reverse order of their construction. Then, when main() returns, a is destructed as per §3.6.3 in the standard: "Destructors for initialized objects (...) with static storage duration are called as a result of returning from main."
According to the C++11 standard, what is the output of this program? #include <iostream> #include <vector> int f() { std::cout << "f"; return 0;} int g() { std::cout << "g"; return 0;} void h(std::vector<int> v) {} int main() { h({f(), g()}); }
Answer This question The program is guaranteed to output:. Its output is "fg". Explanation The goal of this question is to demonstrate that the evaluation order of elements in an initializer list is specified (as opposed to the arguments to a function call). §8.5.4¶4: Within the initializer-list of a braced-init-list, the initializer-clauses, including any that result from pack expansions (§14.5.3), are evaluated in the order in which they appear. If h took two ints instead of a vector<int>, and was called like this: h(f(), g()); the program would be unspecified, and could either print fg or gf.
According to the C++11 standard, what is the output of this program? #include <iostream> volatile int a; int main() { std::cout << (a + a); }
Answer This question The program is undefined. Explanation The issue here is not the missing initializer of the variable a - it will implicitly be initialized to 0 here. But the issue is the access to a twice without sequencing between the accesses. According to §1.9¶12, accesses of volatile glvalues are side-effects and according to §1.9¶15 these two unsequenced side-effects on the same scalar object result in undefined behavior.
According to the C++11 standard, what is the output of this program? #include <iostream> typedef long long ll; void foo(unsigned ll) { std::cout << "1"; } void foo(unsigned long long) { std::cout << "2"; } int main() { foo(2ull); }
Answer This question The program is guaranteed to output:. 2 §7.1¶2 in the C++11 standard states, "If a type-name is encountered while parsing a decl-specifier-seq, it is interpreted as part of the decl-specifier-seq if and only if there is no previous type-specifier other than a cv-qualifier in the decl-specifier-seq." §7.1¶3 also has a note: "Since signed, unsigned, long, and short by default imply int, a type-name appearing after one of those specifiers is treated as the name being (re)declared." In void foo(unsigned ll), since unsigned implies int, ll is being redeclared as a parameter name.
According to the C++11 standard, what is the output of this program? #include <iostream> #include <memory> #include <vector> class C { public: void foo() { std::cout << "A"; } void foo() const { std::cout << "B"; } }; struct S { std::vector<C> v; std::unique_ptr<C> u; C *const p; S() : v(1) , u(new C()) , p(u.get()) {} }; int main() { S s; const S &r = s; s.v[0].foo(); s.u->foo(); s.p->foo(); r.v[0].foo(); r.u->foo(); r.p->foo(); }
Answer - AABAA According to §8.3.1.1 in the C++ Standard, "The cv-qualifiers [e.g., const] apply to the pointer and not to the object pointed to." That is, const-ness is shallow with regards to raw pointers and references (and standard types that seek to emulate them, like std::unique_ptr) but not with regard to standard containers such as std::vector. In the code above, the object s is non-const, and so its members all retain their default const-ness and all calls through them invoke the non-const version of C::foo(). However, r refers to its object as a const instance of S. That const-ness changes the behavior of its member v, an std::vector which is "const-correct" in the sense that its operator[] returns const C& (see §23.2.3.16) and therefore invokes the const version of C::foo(). The const-ness of r's referent is also propagated to its members u and p (meaning one could not perform a mutating operation on u, e.g., calling r.u.reset()), but this has no effect on the instance of C that they both point *to*. That is, the pointers themselves become const, but the pointed-to objects remain non-const. Hence, they both still call the non-const version of C::foo(). The const-ness of the member S::p is the same for both s and r. Because it is declared as a const pointer, it does not change const-ness to follow the const-ness of its instance of S but remains a const pointer to a non-const object.
How can we make an class act as an interface in C++? A - By only providing all the functions as virtual functions in the class. B - Defining the class following with the keyword virtual C - Defining the class following with the keyword interface D - Defining the class following with the keyword abstract
Answer : A Explaination There are no keywords in C++ such as abstract and interface.
What is the output of the following program? #include<isotream> using namespace std; main() { char s[] = "Fine"; *s = 'N'; cout<<s<<endl; } A - Fine B - Nine C - Compile error D - Runtime error
Answer : B Explaination *s='N', changes the character at base address to 'N'. #include<isotream> using namespace std; main() { char s[] = "Fine"; *s = 'N'; cout<<s<<endl; }
What is the output of the following program? #include<isotream> using namespace std; void main() { char *s = "C++"; cout<<s<<" "; s++; cout<<s<<" "; } A - C++ C++ B - C++ ++ C - ++ ++ D - Compile error
Answer : B Explaination After s++, s points the string "++". #include<isotream> using namespace std; void main() { char *s = "C++"; cout<<s<<" "; s++; cout<<s<<" "; }
Compiler generates ___ file A - Executable code B - Object code C - Assembly code D - None of the above.
Answer : B Explaination Compilation is the process of translating high level language statements into equivalent machine code, which is object code.
'cin' is an __ A - Class B - Object C - Package D - Namespace
Answer : B Explaination It's an object of istream class.
In the following program f() is overloaded. void f(int x) { } void f(signed x) { } main() { } A - True B - False
Answer : B Explaination No, as both the functions signature is same.
What is the output of the following program? #include<isotream> using namespace std; class abc { void f(); void g(); int x; }; main() { cout<<sizeof(abc)<<endl; } A - 12 B - 4 C - 8 D - Compile error
Answer : B Explaination Only the class member variables constitutes as the size of the class or its object. #include<isotream> using namespace std; class abc { void f(); void g(); int x; }; main() { cout<<sizeof(abc)<<endl; }
A constructor can be virtual. A - True B - False
Answer : B Explaination The purpose of the constructor cannot be overridden in the derived class hence constructor cannot be a virtual.
Choose the invalid identifier from the below A - Int B - bool C - DOUBLE D - __0__
Answer : B Explaination bool is the reserved keyword and cannot be used an identifier name.
Identify the C++ compiler of Linux A - cpp B - g++ C - Borland D - vc++ Show Answer
Answer : B Explaination g++ is GNU C++ compiler for linux. Borland and vc++ (Microsoft visual c++) for windows.
Choose the option not applicable for the constructor. A - Cannot be called explicitly. B - Cannot be overloaded. C - Cannot be overridden. D - None of the above.
Answer : C Explaination A constructor can't be overridden.
Which of the following is not the keyword in C++? A - volatile B - friend C - extends D - this
Answer : C Explaination All the rest are valid keywords of C++.
What is the output of the following program? #include<isotream> using namespace std; main() { char s[] = "hello", t[] = "hello"; if(s==t) cout<<"eqaul strings"; } A - Equal strings B - Unequal strings C - No output D - Compilation error
Answer : C Explaination No output, as we are comparing both base addresses and are not same. #include<isotream> using namespace std; main() { char s[] = "hello", t[] = "hello"; if(s==t) cout<<"eqaul strings"; }
Choose the operator which cannot be overloaded. A - / B - () C - :: D - %
Answer : C Explaination Scope resolution (::) is not permitted to be overloaded.
Which feature of the OOPS gives the concept of reusability? A - Abstraction B - Encapsulation C - Inheritance D - None of the above.
Answer : C Explaination The process of designing a new class (derived) from the existing (base) class to acquire the attributes of the existing is called as inheritance. Inheritance gives the concept of reusability for code/software components.
Runtime polymorphism is done using. A - Function overloading B - Virtual classes C - Virtual functions D - Friend function
Answer : C Explaination Virtual functions gives the ability to override the functionality of base class into the derived class. Hence achieving dynamic/runtime polymorphism.
Designer of C++ programming language. A - Charles Babbage B - Dennis Ritchie C - Brain Kernighan D - Bjarne Stroustrup Show Answer
Answer : D Explaination
The programs machine instructions are store in __ memory segment. A - Data B - Stack C - Heap D - Code
Answer : D Explaination Code segments holds the program instructions and fetched by instruction pointer for execution.
What is the output of the following program? #include<isotream> using namespace std; main() { const int a = 5; a++; cout<<a; } A - 5 B - 6 C - Runtime error D - Compile error
Answer : D Explaination Compile error - constant variable cannot be modified. #include<isotream> using namespace std; main() { const int a = 5; a++; cout<<a; }
What is the size of 'int'? A - 2 B - 4 C - 8 D - Compiler dependent
Answer : D Explaination The size of 'int' depends upon the complier i.e. whether it is a 16 bit or 32 bit.
According to the C++11 standard, what is the output of this program? #include <iostream> struct GeneralException { virtual void print() { std::cout << "G"; } }; struct SpecialException : public GeneralException { void print() override { std::cout << "S"; } }; void f() { throw SpecialException(); } int main() { try { f(); } catch (GeneralException e) { e.print(); } }
Answer G We throw a SpecialException. It is derived from GeneralException, but is caught by value, so e will have the dynamic type GeneralException, not SpecialException. This is known as slicing. Instead, we should have caught it by reference catch (GeneralException& e), then its dynamic type would be SpecialException, and the program would output S.
According to the C++11 standard, what is the output of this program? #include <iostream> int main() { int i = 42; int j = 1; std::cout << i / --j; }
Answer: undefined Integer division by zero is undefined behaviour. According to §5.6.4 in the standard: "If the second operand of / or % is zero the behavior is undefined."
The code below is legal? int x = 5; template <typename T> class x { T member; }; int main(int argc, char** argv) { class x<int> y; return 0; } TRUE OR FALSE
FALSE description: A template class name can not be the same as any other name in the same declarative region. This is also the case for typedef names.
The code below declares and defines variable x extern int x; TRUE OR FALSE
FALSE description: An extern declaration does not define the variable unless it is also initialized in the same statement
True or False, the program below will print NOT EQUAL #include <iostream> struct Foo { }; struct Bar { }; int main(int argc, char** argv) { Foo* f = new Foo; Bar* b = new Bar; if ( f == b ) std::cout << "EQUAL" << std::endl; else std::cout << "NOT EQUAL" << std::endl; return 0; } True OR False
FALSE - correct. description: Distinct pointer types can not be compared with equality operators.
According to the C++11 standard, what is the output of this program? #include <iostream> #include <limits> int main() { int i = std::numeric_limits<int>::max(); std::cout << ++i; }
Signed integer overflow is undefined behaviour according to the standard §5.4: "If during the evaluation of an expression, the result is not mathematically defined or not in the range of representable values for its type, the behavior is undefined." Most implementations will just wrap around, so if you try it out on your machine, you will probably see the same as if you had done std::cout << std::numeric_limits<int>::min(); Relying on such undefined behaviour is however _not_ safe. For an interesting example, see http://stackoverflow.com/questions/7682477/why-does-integer-overflow-on-x86-with-gcc-cause-an-infinite-loop
non-const static member variables must be defined outside of the class for them to be used struct test { static int x; }; int test::x; TRUE OR FALSE
TRUE description: The declaration of a static data member in a class does not define it.
According to the C++11 standard, what is the output of this program? #include <iostream> struct X { X() { std::cout << "X"; } }; struct Y { Y(const X &x) { std::cout << "Y"; } void f() { std::cout << "f"; } }; int main() { Y y(X()); y.f(); }
The compilation error is on the line y.f(), but the source of the problem is Y y(X()); This could be interpreted as a a variable definition (which was the intention of the programmer in this example), or as a definition of a function y, returning an object of type Y, taking a function (with no arguments, returning an object of type X) as its argument. The compiler is required by the standard to choose the second interpretation, which means that y.f() does not compile (since y is now a function, not an object of type Y). Wikipedia has a concise explanation: http://en.wikipedia.org/wiki/Most_vexing_parse, and the standard has more in §6.8. To fix the problem, change Y y(X()) to either Y y{X{}} (modern C++) or Y y((X())) (pre-C++11)
According to the C++11 standard, what is the output of this program? #include <vector> #include <iostream> using namespace std; int main() { std::vector<char> delimiters = { ",", ";" }; cout << delimiters[0]; }
UNDEFINED Here we are trying to initialize a vector<char> using two string literals, not two chars. The initializer-list constructor for template <class T>vector is defined as vector(initializer_list<T>) by §23.3.6.1 in the standard. In our case, vector(initializer_list<char>). The type of a string literal is "array of n const char" (§2.14.5¶8), so clearly the initializer-list constructor is not a match. This problem does however not result in a compiler error, since the compiler is able to find another constructor that matches! §13.3.1.7¶1 explains the rules very clearly: "When objects of non-aggregate class type T are list-initialized, overload resolution selects the constructor in two phases: — Initially, the candidate functions are the initializer-list constructors of the class T and the argument list consists of the initializer list as a single argument [which we have seen didn't match]. — If no viable initializer-list constructor is found, overload resolution is performed again, where the candidate functions are all the constructors of the class T and the argument list consists of the elements of the initializer list [in our case, the two string literals "," and ";" ]". Going back to §23.3.6.1, we find this candidate: template <class InputIterator> vector(InputIterator first, InputIterator last) Note that the type of InputIterator has no link to the type of T in the vector<T>. So even if we are initializing a vector<char>, the two arguments can be of arbitrary type. The only requirement is that they confirm to the concept of InputIterator, which const char[] happens to do. Now the constructor believes it has been passed two iterators to the same sequence, but it has actually been passed iterators to two completely different sequences, "," and ";". §24.2.5¶2 says: "The domain of == for forward iterators is that of iterators over the same underlying sequence.". So the result of this program is undefined.
According to the C++11 standard, what is the output of this program? #include <iostream> extern "C" int x; extern "C" { int y; } int main() { std::cout << x << y; return 0; }
UNDEFINED According to §7.5¶7 in the standard : A declaration directly contained in a linkage-specification is treated as if it contains the extern specifier (§7.1.1) for the purpose of determining the linkage of the declared name and whether it is a definition. extern "C" int x; //is just a declaration extern "C" { int y; } //is a definition And according to §3.2¶3: "Every program shall contain exactly one definition of every non-inline function or variable that is odr-used in that program; no diagnostic required." The result: x is never defined but it is optional for the compiler to print an error. The behaviour of this program is undefined.
From line 6 in the code below which labels can you access using a goto statement? 1 2 3 void foo(int x) 4 { 5 pointa: 6 7 pointb: 8 9 pointc: 10 printf("end of function\n"); 11 } 12 13 int main(int argc, char** argv) 14 { 15 foo(5); 16 17 pointd: 18 19 return 0; 20 }
a, b, c - correct description: Labels have function scope. This means they can be accessed from anywhere within the function where they are defined but not in any other function of the program. Labels are the only construct in C++ with function scope.
What value should be printed for x? #include <iostream> int main() { int x = int() = 3; std::cout << x << std::endl; return 0; } a- 0 b- 3 c- undefined d- won't compile
won't compile - correct description: int() creates a temporary variable which is an rvalue. The temporary variable that is created can not be assigned to since it is an rvalue. Thus this code should not compile.
Which of the following variables can be accessed in foo's function try block handler? void foo(int x) try { int y = 2; throw 1; } catch(int e) { } int main(int argc, char** argv) { foo(3); return 0; }
x and e - correct description: Function parameters are accessible in the try handler. Function local variables are NOT accessible in the try handler.
Will "Hello World" be printed by the program below? int main(int argc, char** argv) { int array[33]; if ( &array[4] < &array[23] ) { std::cout << "Hello World" << std::endl; } return 0; } a- yes b- no c- implementation defined d- unspecified e- undefined
yes- correct description: Pointer comparison with greater and less than relational operators is defined within the same array.
Will "Hello World" be printed by the program below? struct Foo { int x; int y; }; int main(int argc, char** argv) { Foo f; if ( &f.x < &f.y ) { std::cout << "Hello World" << std::endl; } return 0; } a- yes b- no c- implementation defined d- unspecified e- undefined
yes- correct description: Relational operators can be used to do pointer comparison of non-static members in the same object where the definitions of the members is not seperated by an access specifier. The member declared first will evaluate to lower. Note: other than this case, the only other time relational operators can be used to compare pointers is when the addresses point to elements in the same array. For all other cases, the result of relational operators on pointers is unspecified.
What value is printed out for the variable x? #include <iostream> int x; int main() { int y; std::cout << x << std::endl; std::cout << y << std::endl; return 0; } a- undefined b- zero
zero - correct description: variables with static storage duration are zero initialized. Note that x has static storage duration even though the static keyword is not used. According to the standard: "All objects which do not have dynamic storage duration, do not have thread storage duration, and are not local have static storage duration"