TCS Papers: Sample Questions 358 - 359 of 502

Examrace Placement Series prepares you for the toughest placement exams to top companies.

Question number: 358

» Languages » C & C Plus Plus

Essay Question▾

Describe in Detail

What does static variable mean?

Explanation

  • There are 3 main uses for the static variable.

    • If you declare within a function: It retains the value between function calls

    • If it is declared for a function name: By default function is extern- visible from other files. If function declaration is static- it is invisible for the outer files

    • Static for global variables: By default global variables are ‘auto’ visible from outside files Static global variable are limited in scope to within the file.

  • Example

  1. #include int t = 10;
  2. main()
  3. {
  4.     int x = 0;
  5.     void funct1();
  6.     funct1();
  7.     printf("After first call  ");
  8.     funct1();
  9.     printf("After second call  ");
  10.     funct1();
  11.     printf("After third call  ");
  12. }
  13. void funct1()
  14. {
  15.     static int y = 0;
  16.     int z = 10;
  17.     printf("value of y %d z %d",y,z);
  18.     y=y+10;
  19. }

Output:

value of y 0 z 10- After first call

value of y 10 z 10- After second call

value of y 20 z 10- After third call

Question number: 359

» Languages » C & C Plus Plus

MCQ▾

Question

Which of the following correctly describes overloading of functions?

Choices

Choice (4) Response

a.

Pseudo polymorphism

b.

Virtual polymorphism

c.

Transient polymorphism

d.

Ad-hoc polymorphism

Answer

d.

Explanation

  • Ad-hoc polymorphism correctly describes overloading of functions.

  • Allows functions with the same name to act differently based on type of arguments.

  • Have different names in C++.

    • Subtype polymorphism is also known as runtime polymorphism.

    • Parametric polymorphism is also known as compile-time polymorphism.

    • Ad-hoc polymorphism is also known as overloading.

    • Coercion is also known as (implicit or explicit) casting – related concept

  • For example, given two ints and the + operator, it adds them together. Given two std: : strings it concatenates them together. This is called overloading. Depending on the type of operands different functions are invoked.

  • Here is a concrete example that implements function add for ints and strings,

  • Example: -

  1. #include <iostream>
  2. #include <string>
  3. int add(int aint b)
  4. {
  5.     return a + b;
  6. }
  7. std::string add(const char *aconst char *b)
  8. {
  9.     std::string result(a);
  10.     result += b;
  11.     return result;
  12. }
  13. int main()
  14. {
  15.     std::cout << add(813) << std::endl;
  16.     std::cout << add("hello ""friends") << std::endl;
  17. }
  • Output:

    21

    Hello friends

  • Ad-hoc polymorphism also appears in C++ if you specialize templates.