Answer the following C++ fundamentals questions.
1) Virtual function dispatch: predict output
Consider this C++ program:
#include <iostream>
using namespace std;
struct Base {
Base() { cout << "Base()\n"; }
virtual void vf() { cout << "Base::vf\n"; }
void nvf() { cout << "Base::nvf\n"; }
virtual ~Base() { cout << "~Base()\n"; }
};
struct Derived : Base {
Derived() { cout << "Derived()\n"; }
void vf() override { cout << "Derived::vf\n"; }
void nvf() { cout << "Derived::nvf\n"; }
~Derived() override { cout << "~Derived()\n"; }
};
int main() {
Base* p = new Derived();
p->vf();
p->nvf();
delete p;
}
-
What is the exact output (line by line)?
-
Explain why each line prints (virtual dispatch vs non-virtual binding, and destructor behavior).
2) Destructors and dangling pointers
For each snippet below:
-
identify whether it is correct, leaks memory, causes undefined behavior, or creates a dangling pointer;
-
explain why;
-
show a safer/fixed version.
(a)
int* make() {
int x = 42;
return &x;
}
(b)
int* p = new int(7);
delete p;
cout << *p << "\n";
(c)
int* p = new int(7);
int* q = p;
delete p;
delete q;
3) Pointer vs reference
Explain the differences between pointers and references in C++ (at least: nullability, reseating, ownership semantics, parameter passing, const behavior), and give examples of when you would choose each.