Menu
CoddyTech

Composition by Value

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

A GDScript member that holds an object stores a reference: the Envelope and the caller share one Badge, so renaming b shows through e.badge. A RefCounted component lives as long as any reference to it, and a Node child is freed with its parent. C++ can compose independent member values: Envelope e{b} copies b into e.badge. C++ value members are constructed and destroyed with their owner. A has-a relationship need not involve dynamic allocation.

GDScript

extends Node

class Badge:
    var name: String
    func _init(n: String) -> void:
        name = n

class Envelope:
    var badge: Badge
    func _init(b: Badge) -> void:
        badge = b

func _ready() -> void:
    var b := Badge.new("Ada")
    var e := Envelope.new(b)
    b.name = "Bo"
    print(e.badge.name)

C++

#include <iostream>
#include <string>
#include <vector>
#include <array>
#include <map>
#include <set>
#include <algorithm>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <utility>
struct Badge{std::string name;};struct Envelope{Badge badge;};
int main(){
Badge b{"Ada"};Envelope e{b};b.name="Bo";std::cout<<e.badge.name<<"\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: nonnegative unit price, quantity, and flat shipping. Order owns an Item by value. Item.subtotal is price times quantity; Order.total adds shipping to its owned item subtotal.

Editable modules: Item.cpp, Item.hpp, Order.cpp, Order.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 "Item.hpp"
#include "Order.hpp"
#include <iostream>
int main(){
{Item i(7,2);Order a(i,3),b(Item(2,4),1);if(i.subtotal()!=14||a.total()!=17||b.total()!=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 p,q,s;in>>p>>q>>s;Item i(p,q);Order o(i,s);std::cout<<o.total()<<"\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 GDScript Developers

Practice on your own: Online C++ compiler