Menu
CoddyTech

Shared Static Members

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

A JavaScript static field lives on the class constructor itself: instances do not see it at all, and assigning the same name on an instance just creates an unrelated own property. C++ static members are explicitly declared. A C++ static member belongs to the class rather than an instance. Static functions have no this pointer.

JavaScript

class Bag {
  static category = "tools";
}
const a = new Bag();
a.category = "books";
console.log(a.category, Bag.category, new Bag().category);

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 JavaScript Developers

Practice on your own: Online C++ compiler