All Courses
OOP: APPENDIX

OOP Viva Tricky Questions and Answers

Use this file for fast viva revision. Each answer starts with the short version first. If the teacher pushes, use the "Explain" part.

Super-Fast One-Line Answers

Question Viva answer
What is OOP? A programming style that groups data and behavior into objects.
What are the four pillars? Encapsulation, Inheritance, Polymorphism, and Abstraction.
Class vs object? Class is a blueprint; object is a real instance created from that blueprint.
Constructor? Special member function automatically called when an object is initialized.
Destructor? Special member function automatically called when an object is destroyed.
Can constructor return value? No, constructors have no return type, not even void.
Can destructor return value? No, destructors have no return type.
Can constructor be overloaded? Yes, constructors can be overloaded by parameter list.
Can destructor be overloaded? No, a class has only one destructor.
Can constructor be virtual? No.
Can destructor be virtual? Yes, and base classes used polymorphically should have virtual destructors.
Pointer vs reference? Pointer stores an address and can be null/reassigned; reference is an alias and must bind to an object.
Why friend function? To let a non-member function access private/protected members when necessary.
Why friend in << overloading? Because left operand is std::ostream, so the overload must be non-member; friend is used if private access is needed.
Function overloading vs operator overloading? Function overloading reuses function names; operator overloading gives operator syntax to user-defined types.
Can function overloading replace operator overloading? Logic-wise yes, syntax-wise no. add(a,b) can replace a+b, but it will not use operator syntax.
Why one parameter in member binary operator? The left operand is implicit as this; the right operand is the explicit parameter.
Why two parameters in non-member binary operator? There is no this, so both operands must be parameters.
Empty class size? At least 1 byte so distinct objects can have distinct addresses.
Callback? A function or callable passed to another function so it can be called later.

Constructors and Destructors

1. What is a constructor?

Short: A constructor initializes an object when it is created.

Explain: It has the same name as the class, no return type, and is selected automatically during object initialization.

class Student {
public:
    Student() {
        // constructor
    }
};

2. Does a constructor allocate memory?

Short: Not usually. Memory for the object is obtained before the constructor body runs.

Explain: Object creation has two broad steps:

  1. Storage is obtained for the object.
  2. The constructor initializes that storage into a valid object.

Inside a constructor, the programmer may allocate extra dynamic memory using new, but that is not the constructor's automatic job.

3. How is a constructor called automatically?

Short: When an object is initialized, the compiler inserts the constructor call.

Student s;        // calls default constructor
Student s2("A");  // calls matching parameterized constructor

Explain: You do not call it like s.Student(). Constructors are invoked by initialization syntax.

4. What is the construction sequence in inheritance?

Short: Virtual base classes, direct base classes, data members, then constructor body.

Explain:

  1. Virtual bases are initialized first.
  2. Direct bases are initialized in the order listed in the base-specifier list.
  3. Non-static data members are initialized in the order declared in the class.
  4. The constructor body runs last.

Destructor order is the reverse of construction.

5. If initializer list order is different, which order is used?

Short: Declaration order, not initializer-list order.

class Demo {
    int a;
    int b;
public:
    Demo() : b(2), a(1) {}
};

a initializes before b because a is declared first.

6. Default constructor vs constructor with default arguments?

Short: A default constructor is any constructor callable with no arguments.

class A {
public:
    A(); // default constructor
};

class B {
public:
    B(int x = 0); // also callable with no arguments, so it is a default constructor too
};

Viva trap: If both A() and A(int x = 0) exist, A a; may become ambiguous or invalid because both can be called with no arguments.

7. What is an implicit default constructor?

Short: If no constructor is declared, the compiler declares a default constructor for you.

Explain: Once you declare any constructor yourself, the compiler stops automatically providing the no-argument default constructor unless you write it or use = default.

class Student {
public:
    Student(int id) {}
};

// Student s; // error: no default constructor

8. What is an explicit constructor?

Short: A constructor marked explicit cannot be used for automatic implicit conversion.

class Number {
public:
    explicit Number(int value) {}
};

Number n1(10);    // ok
// Number n2 = 10; // not allowed with explicit

9. What is implicit vs explicit constructor call?

Short:

  • Implicit style: Student s = Student("A"); or conversion-style construction.
  • Explicit/direct style: Student s("A");

Better viva answer: Constructors are selected by initialization rules. explicit controls whether a constructor can be used for implicit conversions.

10. Can a programmer call a destructor manually?

Short: Yes, but normally you should not.

obj.~Student(); // legal, but dangerous in normal code

Explain: Destructors are automatically called when stack objects go out of scope or when heap objects are deleted. Manual destructor calls are mainly for advanced placement-new/manual lifetime cases. Calling a destructor manually and then letting it run again causes undefined behavior.

11. When does destructor run?

Short:

  • Stack object: at end of scope.
  • Heap object: when delete is used.
  • Member object: when containing object is destroyed.
  • Base/derived: derived destructor first, then base destructor.

12. Why virtual destructor?

Short: To correctly destroy derived objects through base class pointers.

class Base {
public:
    virtual ~Base() = default;
};

If Base* p = new Derived(); delete p; and Base destructor is not virtual, the derived destructor may not run correctly.

Operator Overloading and Friend Functions

13. What is operator overloading?

Short: Giving a built-in operator a meaning for user-defined types.

Point c = a + b;

The compiler translates this into a call to an operator function such as a.operator+(b) or operator+(a, b).

14. Why do we use friend functions in operator overloading?

Short: When the operator function must be non-member but still needs private access.

Common cases:

  • operator<< and operator>>
  • symmetric binary operators where left operand is not your class
  • operators needing private data from two classes

15. Why is operator<< usually a friend?

Short: Because the left operand is std::ostream, not your class.

std::cout << obj;

If implemented as a member of MyClass, the syntax would be wrong:

obj << std::cout; // not natural

So we write it as a non-member:

friend std::ostream& operator<<(std::ostream& os, const MyClass& obj);

It is only a friend if it needs direct access to private data.

16. Is every operator overload a friend?

Short: No.

Use a member function when the left operand is your object and private access is natural:

Point operator+(const Point& other) const;

Use a non-member/friend when the left operand is not your class or you want symmetric conversions.

17. Why do we pass one parameter to a binary member operator overload?

Short: Because the left operand is already the current object, available through this.

class Point {
public:
    Point operator+(const Point& other) const;
};

For a + b:

  • a is this
  • b is other

18. Why do non-member binary operators take two parameters?

Short: Because non-member functions do not have this.

Point operator+(const Point& left, const Point& right);

19. Can function overloading be used instead of operator overloading?

Short: Yes for behavior, no for operator syntax.

Point add(Point a, Point b); // function overloading possible
Point c = add(a, b);

But if you want:

Point c = a + b;

then you need operator overloading.

20. Is operator overloading a form of function overloading?

Short: Yes, operator functions are functions with special names like operator+.

Explain: The compiler chooses among overloaded operator functions based on operand types.

21. Can we create new operators?

Short: No.

You cannot create operator** for exponentiation. You can only overload existing operators.

22. Which operators cannot be overloaded?

Short:

  • :: scope resolution
  • . member access
  • .* pointer-to-member access
  • ?: conditional operator

23. Why can some operators not be overloaded?

Short: Because the language needs their meaning fixed for parsing, member lookup, and core control rules.

Explain: If . or :: could be redefined, the compiler could not reliably understand basic class/member access. If ?: could be changed, fundamental conditional expression behavior would become unstable.

24. Can operator precedence be changed?

Short: No.

If you overload +, it still has the same precedence as built-in +.

25. Can operator associativity be changed?

Short: No.

Overloading changes behavior for user-defined types, not grammar rules.

26. Can we overload operators for built-in types only?

Short: No.

At least one operand must be a user-defined class or enum type. You cannot redefine int + int.

27. Which operators must be member functions?

Short: Common viva list:

  • operator=
  • operator[]
  • operator()
  • operator->

28. Why return stream reference from operator<<?

Short: To allow chaining.

std::cout << a << b << c;

So return std::ostream&.

29. Why pass object by const reference in operator<<?

Short: To avoid copying and promise not to modify the object.

std::ostream& operator<<(std::ostream& os, const Student& s);

30. Why pass object by non-const reference in operator>>?

Short: Because input modifies the object.

std::istream& operator>>(std::istream& is, Student& s);

Function Overloading, Overriding, and Binding

31. What is function overloading?

Short: Same function name, different parameter list, compile-time selection.

void print(int);
void print(double);
void print(std::string);

32. Can functions be overloaded only by return type?

Short: No.

int show();
double show(); // invalid if parameter list is same

33. What is function overriding?

Short: A derived class redefines a base class virtual function with the same signature.

class Base {
public:
    virtual void speak();
};

class Derived : public Base {
public:
    void speak() override;
};

34. Overloading vs overriding?

Short:

  • Overloading: same scope/name, different parameters, compile-time.
  • Overriding: base/derived relationship, same signature, runtime if virtual.

35. What is static binding?

Short: Function call resolved at compile time.

Examples:

  • normal function calls
  • function overloading
  • operator overloading

36. What is dynamic binding?

Short: Function call resolved at runtime through virtual functions.

Required:

  • inheritance
  • virtual function
  • base pointer/reference
  • overriding

Callback Mechanism

37. What is a callback?

Short: A callback is a function or callable object passed to another function to be called later.

#include <iostream>

void greet() {
    std::cout << "Hello\n";
}

void runCallback(void (*callback)()) {
    callback();
}

int main() {
    runCallback(greet);
}

38. Why use callbacks?

Short: To make code flexible. The caller decides what action should happen later.

Examples:

  • button click handler
  • sorting comparison function
  • event system
  • timer action

39. Callback vs normal function call?

Short:

  • Normal call: I call the function now.
  • Callback: I give you the function; you call it later.

40. Callback in OOP?

Short: Use function pointers, functor objects, lambdas, interfaces, or std::function.

#include <functional>
#include <iostream>

void process(const std::function<void()>& callback) {
    callback();
}

int main() {
    process([] {
        std::cout << "Done\n";
    });
}

Pointers and References

41. What is a pointer?

Short: A variable that stores the address of another object.

int x = 10;
int* p = &x;

42. What is a reference?

Short: An alias for an existing object.

int x = 10;
int& r = x;

43. Pointer vs reference?

Feature Pointer Reference
Null allowed? Yes Normally no
Reassignment? Can point to another object Cannot be rebound
Syntax p->x, *p normal variable syntax
Must initialize? No, but should Yes
Use case optional object, dynamic memory, arrays aliasing, parameters, no-copy passing

44. When should we use pointer?

Short:

  • Object may be absent: use pointer or smart pointer.
  • Need dynamic ownership: use std::unique_ptr or std::shared_ptr.
  • Need polymorphic heap object: use smart pointer to base.

45. When should we use reference?

Short:

  • Object must exist.
  • Function should avoid copying.
  • Function should modify caller's object.
void update(Student& s);             // may modify
void print(const Student& s);        // no copy, no modification

46. Why pass object by const reference?

Short: Efficient and safe.

It avoids copying large objects and prevents modification.

47. Can reference be null?

Short: A valid reference should not be null.

Explain: You can create invalid reference behavior using bad pointer tricks, but that is undefined behavior territory and not normal C++.

48. Can pointer be uninitialized?

Short: Yes, but it is dangerous.

Always initialize:

int* p = nullptr;

Memory, Object Size, and Empty Class

49. Why does an empty class have size 1 byte?

Short: So two different objects can have different addresses.

class Empty {};

Empty a;
Empty b;

If sizeof(Empty) were 0, a and b could occupy the same address, breaking the rule that distinct objects should have distinct addresses.

50. Does an empty class really store data?

Short: No meaningful data, but it still occupies at least 1 byte as a complete object.

Viva bonus: Empty base class optimization can remove storage cost when an empty class is used as a base class.

51. Does every object occupy memory?

Short: A complete object occupies storage. Its size depends on data members, padding, alignment, virtual table pointer, and inheritance.

52. Does a member function increase object size?

Short: Usually no.

Member functions are stored as code, not separately inside every object. But virtual functions commonly add a hidden vptr per object.

53. Does constructor occupy memory in object?

Short: No. Constructor code exists like a function. It initializes object memory but is not stored inside each object.

Automatic Compiler Functions

54. Which functions can the compiler generate automatically?

Short: The special member functions:

  • default constructor
  • destructor
  • copy constructor
  • copy assignment operator
  • move constructor
  • move assignment operator

Modern viva answer: Prefer Rule of Zero: use standard library members so compiler-generated functions are correct.

55. What is copy constructor?

Short: Creates a new object from an existing object of the same class.

Student b = a;

56. What is copy assignment?

Short: Assigns one existing object to another existing object.

Student a;
Student b;
b = a;

57. Copy constructor vs assignment operator?

Short:

  • Copy constructor creates a new object.
  • Assignment operator updates an already existing object.

58. What is shallow copy?

Short: Copies raw member values, including pointer addresses.

Danger: Two objects may point to the same dynamic memory.

59. What is deep copy?

Short: Copies the pointed-to data into separate memory.

Use when a class owns raw dynamic memory. Better modern answer: avoid raw ownership and use RAII containers/smart pointers.

Friend Functions and Encapsulation

60. Does friend function break encapsulation?

Short: It weakens encapsulation if overused.

Explain: A friend is allowed private access, so use it only when it makes the interface cleaner or is required by operator syntax.

61. Is friendship mutual?

Short: No.

If A declares B as friend, B can access A; A cannot automatically access B.

62. Is friendship inherited?

Short: No.

A friend of a base class is not automatically a friend of the derived class.

63. Is friendship transitive?

Short: No.

If A is friend of B, and B is friend of C, A is not automatically friend of C.

Inheritance and Polymorphism Traps

64. Why use inheritance?

Short: To model a true is-a relationship and enable polymorphism.

Example: Dog is an Animal.

65. When should we avoid inheritance?

Short: When the relationship is has-a.

Example: Car has an Engine, so use composition.

66. What is abstraction?

Short: Hiding implementation details and exposing only essential operations.

67. What is encapsulation?

Short: Binding data and methods together and protecting internal state from direct outside access.

68. Abstraction vs encapsulation?

Short:

  • Encapsulation hides data/state.
  • Abstraction hides complexity/implementation.

69. Can abstract class have constructor?

Short: Yes.

Explain: You cannot instantiate the abstract class directly, but its constructor runs when a derived object is created.

70. Can abstract class have data members?

Short: Yes.

An abstract class only needs at least one pure virtual function. It may also contain data and normal methods.

71. Can virtual function be private?

Short: Yes.

Access control and virtual dispatch are separate ideas. A private virtual function can still be overridden, but cannot be called from outside.

72. Can static function be virtual?

Short: No.

Virtual dispatch needs an object. Static functions belong to the class, not to a specific object.

73. Why use override?

Short: It lets the compiler check that you really overrode a base virtual function.

It catches spelling mistakes and signature mismatches.

74. What is pure virtual function?

Short: A virtual function declared with = 0.

virtual void draw() = 0;

It makes the class abstract and forces derived classes to implement it unless they remain abstract.

Last-Night Viva Formula

For every tricky question, answer in this pattern:

  1. Definition.
  2. Why it exists.
  3. Tiny code example.
  4. One warning/trap.

Example:

Question: Why friend in operator<<?

Answer: operator<< for cout << obj must be non-member because the left operand is std::ostream, not my class. If it needs private access, I declare it as friend. It returns ostream& so chaining works. Trap: friend is not mandatory if public getters are enough.

Sources Used