Menu
CoddyTech

Virtual Dispatch

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

Swift class methods are dynamically dispatched by default: an override is chosen through any reference typed as the base class unless the method is final, and structs have no inheritance at all. C++ inverts the default: a call through a base pointer or reference dispatches dynamically only when the base declares the function virtual. Polymorphic deletion needs a virtual destructor; copying a derived object into a base value slices it, which never happens to a Swift class reference.

Swift

class Sound {
    func play() -> String { "tap" }
}
class Chime: Sound {
    override func play() -> String { "ding" }
}
let s: Sound = Chime()
print(s.play())

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 Swift Developers

Practice on your own: Online C++ compiler