This question evaluates a candidate's understanding of C++ virtual function dispatch, destructor and object lifetime semantics, stack versus heap allocation, dangling-pointer and double-delete pitfalls, and pointer versus reference distinctions within the Software Engineering Fundamentals domain and the C++ language.
Answer the following C++ fundamentals questions.
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;
}
For each snippet below:
int* make() {
int x = 42;
return &x;
}
int* p = new int(7);
delete p;
cout << *p << "\n";
int* p = new int(7);
int* q = p;
delete p;
delete q;
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.