C++ Virtual Destruction and String to Integer Conversion
1) Consider the following classes:
#include <memory>
struct Base {virtual void f();
};
struct Derived : Base {};
void f() {std::unique_ptr<Base> b = std::make_unique<Derived>();
}
void f() {Base* b = new Derived();
// ...
delete b;
}
int main() {f();
return 0;
}
2) Implement a function to convert a string to a number.
// function to convert string to a number
// 32 signed integer with sign
int convert(std::string str) {
int num = 0;
return num;
}
int main() {
// Given string of number
char s[] = "-123";
int str2num = convert(s);
std::cout << "number -" << str2num << std::endl;
return 0;
}
What is wrong with the first snippet, and how would you correctly implement the string-to-integer conversion in the second snippet?
This question combines two classic C++ interview topics. The first part tests understanding of polymorphic deletion: deleting a `Derived` object through a `Base*` is only safe when the base class has a virtual destructor, and `std::unique_ptr<Base>` is the proper RAII approach. The second part asks for a robust string-to-integer conversion, which should handle optional sign characters, digit accumulation, and overflow/underflow checks while rejecting invalid input.