Menu
CoddyTech

Shared Static Members

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

A GDScript static var belongs to the class rather than to an instance: Bag.count and the methods of every instance see the same value, while an ordinary var is created again for each instance. A static func has no self, so it cannot touch instance members. C++ static members are explicitly declared with static in the same way. A C++ static member belongs to the class rather than an instance. Static functions have no this pointer and are called through the class name.

GDScript

extends Node

class Bag:
    static var count: int = 0
    var items: Array = []
    func _init() -> void:
        count += 1

func _ready() -> void:
    var a := Bag.new()
    var b := Bag.new()
    a.items.append("pen")
    print(Bag.count, " ", a.items.size(), " ", b.items.size())

C++

#include <iostream>
#include <string>
#include <vector>
#include <array>
#include <map>
#include <set>
#include <algorithm>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <utility>
struct Scale {static int double_value(int n){return 2*n;}};
int main(){
std::cout<<Scale::double_value(6)<<"\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 object count. Ticket assigns consecutive IDs starting at 1 from shared next_. reset resets next_ to 1. Driver constructs n tickets and returns their ID sum.

Editable modules: Ticket.cpp, Ticket.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 "Ticket.hpp"
#include <iostream>
int main(){
{Ticket::reset();Ticket a,b;if(a.id()!=1||b.id()!=2)return 21;Ticket::reset();Ticket c;if(c.id()!=1||a.id()!=1)return 22;}
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 n;in>>n;Ticket::reset();int sum=0;for(int i=0;i<n;++i){Ticket t;sum+=t.id();}std::cout<<sum<<"\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