Menu
CoddyTech

Shared Static Members

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

PHP static properties and methods are declared with static and reached through Bag::, self:: or static::; a static method has no $this. Their values last only for the current request, since each PHP request starts from a fresh state. A C++ static member belongs to the class rather than an instance and lives for the whole program run. Static functions have no this pointer.

PHP

<?php
class Bag {
    public static int $made = 0;
    public function __construct() {
        self::$made++;
    }
    public static function report(): string {
        return "made " . self::$made;
    }
}
new Bag();
new Bag();
echo Bag::report(), "\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 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 PHP Developers

Practice on your own: Online C++ compiler