Menu
CoddyTech

Virtual Dispatch

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

R S3 dispatch is always dynamic: UseMethod() looks at the class vector of the actual argument at call time, and NextMethod() continues with the next class in that vector. C++ requires virtual and must avoid slicing when using base values. C++ virtual calls through base pointers or references dispatch dynamically. Polymorphic deletion needs a virtual destructor; copying into a base value can slice.

R

label <- function(x) UseMethod("label")
label.base <- function(x) "base"
label.child <- function(x) paste0(NextMethod(), "!")
obj <- structure(list(), class = c("child", "base"))
cat(label(obj), "\n")

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

Practice on your own: Online C++ compiler