Time *submissions[20] = { new Time(10, 22), new Time(13, 45), new MilTime(13, 18), new MilTime(23, 0), new MilTime(5, 10), new Time(1, 15) }; ... for(int i = 0; submissions[i] != nullptr; ++i) { submissions[i]->print(cout); cout << endl; }
class Insect { public: Insect(std::string species); }; class Firefly { public: Firefly(std::string species) : Insect(species) { // more code } };
class Student { string name; string address; double total_grade_points, total_credits; Schedule *schedule; public: Student() : schedule{new Schedule} { } double gpa() const { return total_grade_points / total_credits; } virtual void add(Course *new_course); };
~Student() { delete schedule; }
virtual ~Student() { delete schedule; }
void doSomethingNice() { Student someStudent; ... // destructor called here }
class AbstractContainer { public: virtual double& operator[](int index) = 0; virtual int size() = 0; virtual ~AbstractContainer() { } };
void swapFirstLast(AbstractContainer &nums) { int last_index = nums.size() - 1; assert(last_index > 0); // last_index can be 0! double first = nums[0]; nums[0] = nums[last_index]; nums[last_index] = save; } ... declare xs to be some class derived from AbstractContainer ... and read data into the container // first shall be last, last shall be first: swapFirstLast(xs);
double* p = &nums[0]; *p = nums[last_index];
{ int n; cin >> n; FixedVector xs(n); ... { FixedVector ys(n * 2); ... } // ys destroyed here ... } // xs destroyed here
void initializeUpSequence(AbstractContainer *container, double start, double step) { double value = start; for(int ix = 0; ix < container->size(); ++ix) { (*container)[ix] = value; value += step; } } ... AbstractContainer *some_numbers = new MegaVector(); initializeUpSequence(some_numbers, 1.0, 0.1); double sum = 0.0; for(int i = 0; i < some_numbers->size(); ++i) sum += (*some_numbers)[i];
void initializeUpSequence(AbstractContainer container, double start, double step);(with no *)
void initializeUpSequence(AbstractContainer &container, double start, double step);however, the pointer version makes it more obvious that the object is on the heap
double first_and_last(MegaVector nums) { double sum = nums[0] + nums[nums.size() - 1]; return sum; }
MegaVector xs; ... double s = first_and_last(xs);
double first_and_last(MegaVector &nums) { double sum = nums[0] + nums[nums.size() - 1]; return sum; }
double sum = (nums[0] = 0.0) + nums[nums.size() - 1];
double first_and_last(const MegaVector &nums) { double sum = nums[0] + nums[nums.size() - 1]; return sum; }
bool operator<(const Student &a, const Student &b) { return a.name() < b.name(); }