Menu
CoddyTech

Shared Static Members

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

Kotlin has no static keyword: class-wide members live in a companion object, which is a real singleton object, or at the top level of a file. A C++ static member belongs to the class rather than an instance and is reached as Class::name. Static functions have no this pointer, and a static data member that is not inline needs exactly one definition outside the class.

Kotlin

class Ticket {
    companion object {
        var issued = 0

        fun next(): Int {
            issued += 1
            return issued
        }
    }
}

fun main() {
    Ticket.next()
    println(Ticket.next())
}

C++

#include <iostream>
#include <string>
#include <vector>
#include <array>
#include <map>
#include <set>
#include <algorithm>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <utility>
struct Ticket {static int issued;static int next(){return ++issued;}};
int Ticket::issued=0;
int main(){
Ticket::next();std::cout<<Ticket::next()<<"\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 Kotlin Developers

Practice on your own: Online C++ compiler