Skip to main content

SET PYQs from Unit-3

 Predict the output of this source code written in C++ language :
 class C1 {
   public:
      void display() { cout<<"Hello";}
 };
 class C2; public C1 {
   public:
       void display() { cout<<"World";}
 };
 int main(void) {
 C1*ptr = new C2;
 ptr->display();
 return 0;
 }

You have two classes: 
c1 (base class) and c2 (derived class). Both have a function named display()

In the main() function:
A pointer ptr of type C1* is declared and initialized to point to an object of type C2 (new C2). The display() function is called using the ptr.

Since the display() function in the base class is not virtual, the function resolution is done based on the type of the pointer (compile-time resolution).
Here, ptr is of type C1*, so the base class version of display() is called, and "Hello" is printed.

If you want the derived class display() function to be invoked (i.e., enable runtime polymorphism), you need to declare display() as virtual in the base class.

Consider the following segment of ‘C’ programming code, upon execution it will produce output as:

In C, the auto keyword is used to declare automatic variables. These variables are local to the block in which they are defined and are automatically deallocated when the block is exited

int i = 3 block prints the value of i as 3
int i = 2 block prints the value of i as 3 because int i = 3 is initialized inside this block
int i = 1 block prints the value of i as 2 because int i= 2 is initialized inside this block

Output will be: 3 3 2

Consider the following ‘C’ program fragment:
 int main( ) 
 { 
  char *a, *b, c[10], d[10]; 
  a=b; 
  b=c; 
  c=d; 
  d=a; 
  return Φ; 
 } 
 Choose the statement having error:

Statement a = b assigns b pointer's value to a pointer.
Statement b = c assigns first index value of c array, that is, c[0] to b
Statements c = d and d = a produce the same error: assignment to expression with array type
The error assignment to expression with array type occurs in C when you try to assign a value directly to an array. Arrays in C are not modifiable lvalues, meaning you cannot assign values to them directly.


Comments