Menu
CoddyTech

Virtual Dispatch

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

C# requires virtual or abstract plus override for dispatch, similar in intent to explicit C++ virtual contracts. C++ virtual calls through base pointers or references dispatch dynamically. Polymorphic deletion needs a virtual destructor; copying into a base value can slice.

C#

using System;
using System.Collections.Generic;
using System.Linq;
class Program {
class Sound {public virtual string Play(){return "tap";}} class Chime:Sound {public override string Play(){return "ding";}}
static void Main() {
Sound s=new Chime();Console.WriteLine(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 C# Developers

Practice on your own: Online C++ compiler