Menu
CoddyTech

Virtual Dispatch

Lesson 39 of 48 in Coddy's C++ for C Developers course.

C can emulate dispatch with function pointers, but has no language-level class inheritance. C++ virtual functions select an override through a base reference or pointer. Deleting a derived object through a base pointer requires a virtual base destructor. Passing polymorphic objects by value can slice off the derived part.

C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
const char* ding(void){return "ding";}struct Sound{const char*(*play)(void);};
int main(void){
struct Sound s={ding};puts(s.play());
return 0;
}

C++

#include <iostream>
#include <string>
#include <vector>
#include <array>
#include <map>
#include <set>
#include <algorithm>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <utility>
struct Sound{virtual ~Sound()=default;virtual std::string play()const{return "tap";}};struct Chime:Sound{std::string play()const override{return "ding";}};
int main(){
Chime x;const Sound& s=x;std::cout<<s.play()<<"\n";
}

Trace each program independently. These examples demonstrate the concept with different operations or data from the task; source and target output are not assumed to match.

challenge icon

Challenge

Easy

Input: base charge and bonus, nonnegative. Fee.amount returns base charge. ExtraFee publicly derives from Fee and overrides amount to add bonus. Driver calls via const Fee reference. Use a virtual destructor.

Editable modules: Fee.cpp, Fee.hpp, ExtraFee.cpp, ExtraFee.hpp. Each required type has its own named header and implementation. Preserve all public signatures. The locked main.cpp reads stdin and calls the API directly. It also checks public API behavior independently where stated. Return values rather than printing inside the API. Integer inputs and results fit signed int; text is ASCII unless stated otherwise.

Try it yourself

#include "Fee.hpp"
#include "ExtraFee.hpp"
#include <iostream>
int main(){
{Fee a(5);ExtraFee b(2,7);const Fee& r=b;if(a.amount()!=5||r.amount()!=9)return 21;}
std::vector<std::string> rows; std::string line; while(std::getline(std::cin,line)) rows.push_back(line);
std::istringstream in(rows.empty()?"":rows[0]);int a,b;in>>a>>b;ExtraFee f(a,b);const Fee& ref=f;std::cout<<ref.amount()<<"\n";
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in C++ for C Developers

Practice on your own: Online C++ compiler