# Source: https://configcat.com/docs/sdk-reference/cpp.md

# C++ SDK Reference

Copy page

[![Star on GitHub](https://img.shields.io/github/stars/configcat/cpp-sdk.svg?style=social)](https://github.com/configcat/cpp-sdk/stargazers) [![Build Status](https://img.shields.io/github/actions/workflow/status/configcat/cpp-sdk/cpp-ci.yml?logo=GitHub\&label=windows%20%2F%20macos%20%2F%20linux\&branch=main)](https://github.com/configcat/cpp-sdk/actions/workflows/cpp-ci.yml) [![Coverage Status](https://codecov.io/gh/configcat/cpp-sdk/branch/main/graph/badge.svg?token=cvUgfof8k7)](https://codecov.io/gh/configcat/cpp-sdk)

[ConfigCat C++ SDK on GitHub](https://github.com/configcat/cpp-sdk)

## Getting Started[​](#getting-started "Direct link to Getting Started")

### 1. Add the ConfigCat SDK to your project[​](#1-add-the-configcat-sdk-to-your-project "Direct link to 1. Add the ConfigCat SDK to your project")

With **[Vcpkg](https://github.com/microsoft/vcpkg)**

* On Windows:

  ```cmd
  git clone https://github.com/microsoft/vcpkg
  .\vcpkg\bootstrap-vcpkg.bat
  .\vcpkg\vcpkg install configcat

  ```

  In order to use vcpkg with Visual Studio, run the following command (may require administrator elevation):

  ```cmd
  .\vcpkg\vcpkg integrate install

  ```

  After this, you can create a New non-CMake Project (or open an existing one). All installed libraries are immediately ready to be `#include`d and used in your project without additional setup.

* On Linux/Mac:

  ```bash
  git clone https://github.com/microsoft/vcpkg
  ./vcpkg/bootstrap-vcpkg.sh
  ./vcpkg/vcpkg install configcat

  ```

### 2. Include *configcat.h* header in your application code[​](#2-include-configcath-header-in-your-application-code "Direct link to 2-include-configcath-header-in-your-application-code")

```cpp
#include <configcat/configcat.h>

using namespace configcat;

```

### 3. Create the *ConfigCat* client with your *SDK Key*[​](#3-create-the-configcat-client-with-your-sdk-key "Direct link to 3-create-the-configcat-client-with-your-sdk-key")

```cpp
auto client = ConfigCatClient::get("#YOUR-SDK-KEY#");

```

### 4. Get your setting value[​](#4-get-your-setting-value "Direct link to 4. Get your setting value")

```cpp
bool isMyAwesomeFeatureEnabled = client->getValue("isMyAwesomeFeatureEnabled", false);
if (isMyAwesomeFeatureEnabled) {
    doTheNewThing();
} else {
    doTheOldThing();
}

```

### 5. Close *ConfigCat* client​[​](#5-close-configcat-client "Direct link to 5-close-configcat-client")

You can safely shut down all clients at once or individually and release all associated resources on application exit.

```cpp
ConfigCatClient::closeAll(); // closes all clients

ConfigCatClient::close(client); // closes a specific client

```

## Setting up the *ConfigCat Client*[​](#setting-up-the-configcat-client "Direct link to setting-up-the-configcat-client")

*ConfigCat Client* is responsible for:

* managing the communication between your application and ConfigCat servers.
* caching your setting values and feature flags.
* serving values quickly in a failsafe way.

`ConfigCatClient::get("#YOUR-SDK-KEY#")` returns a client with default options.

| Properties         | Description                                                                                                                                                                                                                                                                                                                   |
| ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `baseUrl`          | Optional, sets the CDN base url (forward proxy, dedicated subscription) from where the SDK will download the config JSON.                                                                                                                                                                                                     |
| `dataGovernance`   | Optional, defaults to `Global`. Describes the location of your feature flag and setting data within the ConfigCat CDN. This parameter needs to be in sync with your Data Governance preferences. [More about Data Governance](https://configcat.com/docs/advanced/data-governance.md). Available options: `Global`, `EuOnly`. |
| `connectTimeoutMs` | Optional, defaults to `8000ms`. Sets the amount of milliseconds to wait for the server to make the initial connection (i.e. completing the TCP connection handshake). `0` means it never times out during transfer                                                                                                            |
| `readTimeoutMs`    | Optional, defaults to `5000ms`. Sets the amount of milliseconds to wait for the server to respond before giving up. `0` means it never times out during transfer.                                                                                                                                                             |
| `pollingMode`      | Optional, sets the polling mode for the client. [More about polling modes](#polling-modes).                                                                                                                                                                                                                                   |
| `configCache`      | Optional, sets a custom cache implementation for the client. [More about cache](#custom-cache).                                                                                                                                                                                                                               |
| `logger`           | Optional, sets the internal logger and log level. [More about logging](#logging).                                                                                                                                                                                                                                             |
| `flagOverrides`    | Optional, sets the local feature flag & setting overrides. [More about feature flag overrides](#flag-overrides).                                                                                                                                                                                                              |
| `defaultUser`      | Optional, sets the default user. [More about default user](#default-user).                                                                                                                                                                                                                                                    |
| `offline`          | Optional, defaults to `false`. Indicates whether the SDK should be initialized in offline mode. [More about offline mode](#online--offline-mode).                                                                                                                                                                             |
| `hooks`            | Optional, used to subscribe events that the SDK sends in specific scenarios. [More about hooks](#hooks).                                                                                                                                                                                                                      |

```cpp
ConfigCatOptions options;
options.pollingMode = PollingMode::manualPoll();
auto client = ConfigCatClient::get("#YOUR-SDK-KEY#", &options);

```

caution

We strongly recommend you to use the `ConfigCatClient` as a Singleton object in your application. The `ConfigCatClient` constructs singleton client instances for your SDK keys with its `ConfigCatClient::get(<sdkKey>)` static factory method. These clients can be closed all at once with `ConfigCatClient::closeAll()` method or individually with the `ConfigCatClient::close(client)`.

## Anatomy of `getValue()`[​](#anatomy-of-getvalue "Direct link to anatomy-of-getvalue")

| Parameters     | Description                                                                                                                                       |
| -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
| `key`          | **REQUIRED.** The key of a specific setting or feature flag. Set on *ConfigCat Dashboard* for each setting.                                       |
| `defaultValue` | **REQUIRED.** This value will be returned in case of an error.                                                                                    |
| `user`         | Optional, *User Object*. Essential when using Targeting. [Read more about Targeting.](https://configcat.com/docs/targeting/targeting-overview.md) |

```cpp
auto user = ConfigCatUser::create("#USER-IDENTIFIER#");
auto value = client->getValue(
    "keyOfMySetting", // key
    false, // defaultValue
    user, // Optional User Object
);

```

caution

It is important to choose the correct `getValue` overload, where the type of the `defaultValue` parameter matches the type of the feature flag or setting you are evaluating. Please refer to the following table for the corresponding types.

### Setting type mapping[​](#setting-type-mapping "Direct link to Setting type mapping")

| Setting Kind   | Type of `defaultValue`        |
| -------------- | ----------------------------- |
| On/Off Toggle  | `bool`                        |
| Text           | `std::string` / `const char*` |
| Whole Number   | `int32_t`                     |
| Decimal Number | `double`                      |

In addition to the overloads mentioned above, you also have the option to choose an overload that doesn't expect a default value. In that case any setting kind is allowed, and in case of error, the return value will be `std::nullopt`.

If you specify a default value whose type mismatches the setting kind, an error message will be logged and `defaultValue` will be returned.

## Anatomy of `getValueDetails()`[​](#anatomy-of-getvaluedetails "Direct link to anatomy-of-getvaluedetails")

`getValueDetails()` is similar to `getValue()` but instead of returning the evaluated value only, it gives more detailed information about the evaluation result.

| Parameters     | Description                                                                                                                                       |
| -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
| `key`          | **REQUIRED.** The key of a specific setting or feature flag. Set on *ConfigCat Dashboard* for each setting.                                       |
| `defaultValue` | **REQUIRED.** This value will be returned in case of an error.                                                                                    |
| `user`         | Optional, *User Object*. Essential when using Targeting. [Read more about Targeting.](https://configcat.com/docs/targeting/targeting-overview.md) |

```cpp
auto user = ConfigCatUser::create("#USER-IDENTIFIER#");
auto details = client->getValueDetails(
    "keyOfMySetting", // key
    false, // defaultValue
    user, // Optional User Object
);

```

caution

It is important to choose the correct `getValueDetails` overload, where the type of the `defaultValue` parameter matches the type of the feature flag or setting you are evaluating. Please refer to [this table](#setting-type-mapping) for the corresponding types.

The `details` result contains the following information:

| Field                   | Type                              | Description                                                                                                |
| ----------------------- | --------------------------------- | ---------------------------------------------------------------------------------------------------------- |
| `value`                 | `std::optional<Value>`            | The evaluated value of the feature flag or setting.                                                        |
| `key`                   | `std::string`                     | The key of the evaluated feature flag or setting.                                                          |
| `isDefaultValue`        | `bool`                            | True when the default value passed to `getValueDetails()` is returned due to an error.                     |
| `errorMessage`          | `std::optional<std::string>`      | In case of an error, this field contains the error message.                                                |
| `errorException`        | `std::exception_ptr`              | In case of an error, this property contains the related exception object (if any).                         |
| `user`                  | `std::shared_ptr<ConfigCatUser>`  | The User Object that was used for evaluation.                                                              |
| `matchedTargetingRule`  | `std::optional<TargetingRule>`    | The targeting rule (if any) that matched during the evaluation and was used to return the evaluated value. |
| `matchedPercentageRule` | `std::optional<PercentageOption>` | The percentage option (if any) that was used to select the evaluated value.                                |
| `fetchTime`             | `std::chrono::time_point`         | The last download time (UTC) of the current config.                                                        |

## User Object[​](#user-object "Direct link to User Object")

The [User Object](https://configcat.com/docs/targeting/user-object.md) is essential if you'd like to use ConfigCat's [Targeting](https://configcat.com/docs/targeting/targeting-overview.md) feature.

```cpp
auto user = ConfigCatUser::create("#UNIQUE-USER-IDENTIFIER#");

```

```cpp
auto user = ConfigCatUser::create("john@example.com");

```

### Customized User Object creation[​](#customized-user-object-creation "Direct link to Customized User Object creation")

| Argument  | Description                                                                                                                     |
| --------- | ------------------------------------------------------------------------------------------------------------------------------- |
| `id`      | **REQUIRED.** Unique identifier of a user in your application. Can be any value, even an email address.                         |
| `email`   | Optional parameter for easier Targeting Rule definitions.                                                                       |
| `country` | Optional parameter for easier Targeting Rule definitions.                                                                       |
| `custom`  | Optional dictionary for custom attributes of a user for advanced Targeting Rule definitions. e.g. User role, Subscription type. |

```cpp
auto user = ConfigCatUser::create(
    "#UNIQUE-USER-IDENTIFIER#", // userID
    "john@example.com", // email
    "United Kingdom", // country
    {
        { "SubscriptionType", "Pro" },
        { "UserRole", "Admin" }
    } // custom
);

```

The `custom` dictionary also allows attribute values other than `std::string` values:

```cpp
auto user = ConfigCatUser::create(
    "#UNIQUE-USER-IDENTIFIER#", // userID
    "john@example.com", // email
    "United Kingdom", // country
    {
        { "Rating", 4.5 },
        { "RegisteredAt",  make_datetime(2023, 11, 22, 12, 34, 56) },
        { "Roles", std::vector<std::string>{"Role1", "Role2"} }
    } // custom
)

```

### User Object Attribute Types[​](#user-object-attribute-types "Direct link to User Object Attribute Types")

All comparators support `std::string` values as User Object attribute (in some cases they need to be provided in a specific format though, see below), but some of them also support other types of values. It depends on the comparator how the values will be handled. The following rules apply:

**Text-based comparators** (EQUALS, IS\_ONE\_OF, etc.)

* accept `std::string` values,
* all other values are automatically converted to `std::string` (a warning will be logged but evaluation will continue as normal).

**SemVer-based comparators** (IS\_ONE\_OF\_SEMVER, LESS\_THAN\_SEMVER, GREATER\_THAN\_SEMVER, etc.)

* accept `std::string` values containing a properly formatted, valid semver value,
* all other values are considered invalid (a warning will be logged and the currently evaluated Targeting Rule will be skipped).

**Number-based comparators** (EQUALS\_NUMBER, LESS\_THAN\_NUMBER, GREATER\_THAN\_OR\_EQUAL\_NUMBER, etc.)

* accept `double` values and all other numeric values which can safely be converted to `double`,
* accept `std::string` values containing a properly formatted, valid `double` value,
* all other values are considered invalid (a warning will be logged and the currently evaluated Targeting Rule will be skipped).

**Date time-based comparators** (BEFORE\_DATETIME / AFTER\_DATETIME)

* accept `configcat::date_time_t` (`std::chrono::system_clock::time_point`) values, which are automatically converted to a second-based Unix timestamp,
* accept `double` values representing a second-based Unix timestamp and all other numeric values which can safely be converted to `double`,
* accept `std::string` values containing a properly formatted, valid `double` value,
* all other values are considered invalid (a warning will be logged and the currently evaluated Targeting Rule will be skipped).

**String array-based comparators** (ARRAY\_CONTAINS\_ANY\_OF / ARRAY\_NOT\_CONTAINS\_ANY\_OF)

* accept lists of `std::string` (i.e. `std::vector<std::string>`),
* accept `std::string` values containing a valid JSON string which can be deserialized to an array of `std::string`,
* all other values are considered invalid (a warning will be logged and the currently evaluated Targeting Rule will be skipped).

### Default user[​](#default-user "Direct link to Default user")

There's an option to set a default User Object that will be used at feature flag and setting evaluation. It can be useful when your application has a single user only, or rarely switches users.

You can set the default User Object either on SDK initialization:

```cpp
ConfigCatOptions options;
options.defaultUser = ConfigCatUser::create("john@example.com");
auto client = ConfigCatClient::get("#YOUR-SDK-KEY#", &options);

```

or with the `setDefaultUser()` method of the ConfigCat client.

```cpp
client->setDefaultUser(ConfigCatUser::create("john@example.com"));

```

Whenever the `getValue()`, `getValueDetails()`, `getAllValues()`, or `getAllValueDetails()` methods are called without an explicit `user` parameter, the SDK will automatically use the default user as a User Object.

```cpp
auto user = ConfigCatUser::create("john@example.com");
client->setDefaultUser(user);

// The default user will be used at the evaluation process.
auto value = client->getValue("keyOfMySetting", false);

```

When the `user` parameter is specified on the requesting method, it takes precedence over the default user.

```cpp
auto user = ConfigCatUser::create("john@example.com");
client->setDefaultUser(user);

auto otherUser = ConfigCatUser::create("brian@example.com");

// otherUser will be used at the evaluation process.
auto value = client->getValue("keyOfMySetting", false, otherUser.get());

```

For deleting the default user, you can do the following:

```cpp
client->clearDefaultUser();

```

## Polling Modes[​](#polling-modes "Direct link to Polling Modes")

The *ConfigCat SDK* supports 3 different polling strategies to fetch feature flags and settings from the ConfigCat CDN. Once the latest data is downloaded, it is stored in the cache, then calls to `getValue()` use the cached data to evaluate feature flags and settings. With the following polling modes, you can customize the SDK to best fit to your application's lifecycle.<br />[More about polling modes.](https://configcat.com/docs/advanced/caching.md)

### Auto polling (default)[​](#auto-polling-default "Direct link to Auto polling (default)")

The *ConfigCat SDK* downloads the latest config data from the ConfigCat CDN automatically every 60 seconds and stores it in the cache.

Use the `autoPollIntervalInSeconds` option parameter of the `PollingMode::autoPoll()` to change the polling interval.

```cpp
auto autoPollIntervalInSeconds = 100;
ConfigCatOptions options;
options.pollingMode = PollingMode::autoPoll(autoPollIntervalInSeconds);
auto client = ConfigCatClient::get("#YOUR-SDK-KEY#", &options);

```

Available options:

| Option Parameter            | Description                                                                                         | Default |
| --------------------------- | --------------------------------------------------------------------------------------------------- | ------- |
| `autoPollIntervalInSeconds` | Polling interval.                                                                                   | 60      |
| `maxInitWaitTimeInSeconds`  | Maximum waiting time between the client initialization and the first config acquisition in seconds. | 5       |

### Lazy Loading[​](#lazy-loading "Direct link to Lazy Loading")

When calling `getValue()`, the *ConfigCat SDK* downloads the latest config data from the ConfigCat CDN only if it is not already present in the cache, or if the cache has expired. In this case `getValue()` will return the setting value after the cache is updated.

Use the `cacheRefreshIntervalInSeconds` option parameter of the `PollingMode::lazyLoad()` to set cache lifetime.

```cpp
auto cacheRefreshIntervalInSeconds = 100;
ConfigCatOptions options;
options.pollingMode = PollingMode::lazyLoad(cacheRefreshIntervalInSeconds);
auto client = ConfigCatClient::get("#YOUR-SDK-KEY#", &options);

```

Available options:

| Parameter                       | Description | Default |
| ------------------------------- | ----------- | ------- |
| `cacheRefreshIntervalInSeconds` | Cache TTL.  | 60      |

### Manual Polling[​](#manual-polling "Direct link to Manual Polling")

Manual polling gives you full control over when the config data is downloaded from the ConfigCat CDN. The *ConfigCat SDK* will not download it automatically. Calling `forceRefresh()` is your application's responsibility.

```cpp
ConfigCatOptions options;
options.pollingMode = PollingMode::manualPoll();
auto client = ConfigCatClient::get("#YOUR-SDK-KEY#", &options);
client->forceRefresh();

```

> `getValue()` returns `defaultValue` if the cache is empty. Call `forceRefresh()` to update the cache.

## Hooks[​](#hooks "Direct link to Hooks")

The SDK provides several hooks (events), by means of which you can get notified of its actions. You can subscribe to the following events emitted by the *ConfigCat* client:

* `onClientReady()`: This event is emitted when the client reaches the ready state, i.e. completes initialization.

  * If Lazy Loading or Manual Polling is used, it's considered ready right after instantiation.

  * If Auto Polling is used, the ready state is reached as soon as

    <!-- -->

    * the initial sync with the external cache yields up-to-date config data,
    * otherwise, if the client is online (i.e. HTTP requests are allowed), the first config fetch operation completes (regardless of success or failure),
    * or the time specified via Auto Polling's `maxInitWaitTimeInSeconds` option has passed.

  Reaching the ready state usually means the client is ready to evaluate feature flags and settings. However, please note that this is not guaranteed. In case of initialization failure or timeout, the internal cache may be empty or expired even after the ready state is reported. Alternatively, in Auto Polling mode, you can wait for the first `onConfigChanged` event to be notified when the internal cache is actually populated with config data.

* `onConfigChanged(std::shared_ptr<const Settings>)`: This event is emitted first when the client's internal cache gets populated. Afterwards, it is emitted again each time the internally cached config is updated to a newer version, either as a result of synchronization with the external cache, or as a result of fetching a newer version from the ConfigCat CDN.

* `onFlagEvaluated(const EvaluationDetailsBase&)`: This event is emitted each time the client evaluates a feature flag or setting. The event provides the same evaluation details that you would get from [`getValueDetails()`](#anatomy-of-getvaluedetails).

* `onError(const std::string&, const std::exception_ptr&)`: This event is emitted when an error occurs within the client.

You can subscribe to these events either on SDK initialization:

```cpp
ConfigCatOptions options;
options.pollingMode = PollingMode::manualPoll();
options.hooks = std::make_shared<Hooks>(
    []() { /* onClientReady callback */ },
    [](std::shared_ptr<const Settings> config) { /* onConfigChanged callback */ },
    [](const EvaluationDetailsBase& details) { /* onFlagEvaluated callback */ },
    [](const std::string& error, const std::exception_ptr& exception) { /* onError callback */ }
);
auto client = ConfigCatClient::get("#YOUR-SDK-KEY#", &options);

```

or with the `getHooks()` method of the ConfigCat client:

```cpp
client->getHooks->addOnFlagEvaluated([](const EvaluationDetailsBase& details) { /* onFlagEvaluated callback */ });

```

## Online / Offline mode[​](#online--offline-mode "Direct link to Online / Offline mode")

In cases when you'd want to prevent the SDK from making HTTP calls, you can put it in offline mode:

```cpp
client->setOffline();

```

In offline mode, the SDK won't initiate HTTP requests and will work only from its cache.

To put the SDK back in online mode, you can do the following:

```cpp
client->setOnline();

```

> With `client->isOffline()` you can check whether the SDK is in offline mode.

## Flag Overrides[​](#flag-overrides "Direct link to Flag Overrides")

With flag overrides you can overwrite the feature flags & settings downloaded from the ConfigCat CDN with local values. Moreover, you can specify how the overrides should apply over the downloaded values. The following 3 behaviours are supported:

* **Local only** (`OverrideBehaviour::LocalOnly`): When evaluating values, the SDK will not use feature flags & settings from the ConfigCat CDN, but it will use all feature flags & settings that are loaded from local-override sources.

* **Local over remote** (`OverrideBehaviour::LocalOverRemote`): When evaluating values, the SDK will use all feature flags & settings that are downloaded from the ConfigCat CDN, plus all feature flags & settings that are loaded from local-override sources. If a feature flag or a setting is defined both in the downloaded and the local-override source then the local-override version will take precedence.

* **Remote over local** (`OverrideBehaviour::RemoteOverLocal`): When evaluating values, the SDK will use all feature flags & settings that are downloaded from the ConfigCat CDN, plus all feature flags & settings that are loaded from local-override sources. If a feature flag or a setting is defined both in the downloaded and the local-override source then the downloaded version will take precedence.

You can set up the SDK to load your feature flag & setting overrides from a file or a map.

### JSON File[​](#json-file "Direct link to JSON File")

The SDK can be set up to load your feature flag & setting overrides from a file.

#### File[​](#file "Direct link to File")

```cpp
ConfigCatOptions options;
options.flagOverrides = std::make_shared<FileFlagOverrides>("path/to/the/local_flags.json", LocalOnly);
auto client = ConfigCatClient::get("#YOUR-SDK-KEY#", &options);

```

#### JSON File Structure[​](#json-file-structure "Direct link to JSON File Structure")

The SDK supports 2 types of JSON structures to describe feature flags & settings.

##### 1. Simple (key-value) structure[​](#1-simple-key-value-structure "Direct link to 1. Simple (key-value) structure")

```json
{
  "flags": {
    "enabledFeature": true,
    "disabledFeature": false,
    "intSetting": 5,
    "doubleSetting": 3.14,
    "stringSetting": "test"
  }
}

```

##### 2. Complex (full-featured) structure[​](#2-complex-full-featured-structure "Direct link to 2. Complex (full-featured) structure")

This is the same format that the SDK downloads from the ConfigCat CDN. It allows the usage of all features that are available on the ConfigCat Dashboard.

You can download your current config JSON from ConfigCat's CDN and use it as a baseline.

A convenient way to get the config JSON for a specific SDK Key is to install the [ConfigCat CLI](https://github.com/configcat/cli) tool and execute the following command:

```bash
configcat config-json get -f v6 -p {YOUR-SDK-KEY} > config.json

```

(Depending on your [Data Governance](https://configcat.com/docs/advanced/data-governance.md) settings, you may need to add the `--eu` switch.)

Alternatively, you can download the config JSON manually, based on your [Data Governance](https://configcat.com/docs/advanced/data-governance.md) settings:

* GLOBAL: `https://cdn-global.configcat.com/configuration-files/{YOUR-SDK-KEY}/config_v6.json`
* EU: `https://cdn-eu.configcat.com/configuration-files/{YOUR-SDK-KEY}/config_v6.json`

```json
{
  "p": {
    // hash salt, required only when confidential text comparator(s) are used
    "s": "80xCU/SlDz1lCiWFaxIBjyJeJecWjq46T4eu6GtozkM="
  },
  "s": [ // array of segments
    {
      "n": "Beta Users", // segment name
      "r": [ // array of User Conditions (there is a logical AND relation between the elements)
        {
          "a": "Email", // comparison attribute
          "c": 0, // comparator (see below)
          "l": [ // comparison value (see below)
            "john@example.com", "jane@example.com"
          ]
        }
      ]
    }
  ],
  "f": { // key-value map of feature flags & settings
    "isFeatureEnabled": { // key of a particular flag / setting
      "t": 0, // setting type, possible values:
              // 0 -> on/off setting (feature flag)
              // 1 -> text setting
              // 2 -> whole number setting
              // 3 -> decimal number setting
      "r": [ // array of Targeting Rules (there is a logical OR relation between the elements)
        {
          "c": [ // array of conditions (there is a logical AND relation between the elements)
            {
              "u": { // User Condition
                "a": "Email", // comparison attribute
                "c": 2, // comparator, possible values and required comparison value types:
                        // 0  -> IS ONE OF (cleartext) + string array comparison value ("l")
                        // 1  -> IS NOT ONE OF (cleartext) + string array comparison value ("l")
                        // 2  -> CONTAINS ANY OF (cleartext) + string array comparison value ("l")
                        // 3  -> NOT CONTAINS ANY OF (cleartext) + string array comparison value ("l")
                        // 4  -> IS ONE OF (semver) + semver string array comparison value ("l")
                        // 5  -> IS NOT ONE OF (semver) + semver string array comparison value ("l")
                        // 6  -> < (semver) + semver string comparison value ("s")
                        // 7  -> <= (semver + semver string comparison value ("s")
                        // 8  -> > (semver) + semver string comparison value ("s")
                        // 9  -> >= (semver + semver string comparison value ("s")
                        // 10 -> = (number) + number comparison value ("d")
                        // 11 -> <> (number + number comparison value ("d")
                        // 12 -> < (number) + number comparison value ("d")
                        // 13 -> <= (number + number comparison value ("d")
                        // 14 -> > (number) + number comparison value ("d")
                        // 15 -> >= (number) + number comparison value ("d")
                        // 16 -> IS ONE OF (hashed) + string array comparison value ("l")
                        // 17 -> IS NOT ONE OF (hashed) + string array comparison value ("l")
                        // 18 -> BEFORE (UTC datetime) + second-based Unix timestamp number comparison value ("d")
                        // 19 -> AFTER (UTC datetime) + second-based Unix timestamp number comparison value ("d")
                        // 20 -> EQUALS (hashed) + string comparison value ("s")
                        // 21 -> NOT EQUALS (hashed) + string comparison value ("s")
                        // 22 -> STARTS WITH ANY OF (hashed) + string array comparison value ("l")
                        // 23 -> NOT STARTS WITH ANY OF (hashed) + string array comparison value ("l")
                        // 24 -> ENDS WITH ANY OF (hashed) + string array comparison value ("l")
                        // 25 -> NOT ENDS WITH ANY OF (hashed) + string array comparison value ("l")
                        // 26 -> ARRAY CONTAINS ANY OF (hashed) + string array comparison value ("l")
                        // 27 -> ARRAY NOT CONTAINS ANY OF (hashed) + string array comparison value ("l")
                        // 28 -> EQUALS (cleartext) + string comparison value ("s")
                        // 29 -> NOT EQUALS (cleartext) + string comparison value ("s")
                        // 30 -> STARTS WITH ANY OF (cleartext) + string array comparison value ("l")
                        // 31 -> NOT STARTS WITH ANY OF (cleartext) + string array comparison value ("l")
                        // 32 -> ENDS WITH ANY OF (cleartext) + string array comparison value ("l")
                        // 33 -> NOT ENDS WITH ANY OF (cleartext + string array comparison value ("l")
                        // 34 -> ARRAY CONTAINS ANY OF (cleartext) + string array comparison value ("l")
                        // 35 -> ARRAY NOT CONTAINS ANY OF (cleartext) + string array comparison value ("l")
                "l": [ // comparison value - depending on the comparator, another type of value may need
                       // to be specified (see above):
                       // "s": string
                       // "d": number
                  "@example.com"
                ]
              }
            },
            {
              "p": { // Flag Condition (Prerequisite)
                "f": "mainIntFlag", // key of prerequisite flag
                "c": 0, // comparator, possible values: 0 -> EQUALS, 1 -> NOT EQUALS
                "v": { // comparison value (value's type must match the prerequisite flag's type)
                  "i": 42
                }
              }
            },
            {
              "s": { // Segment Condition
                "s": 0, // segment index, a valid index into the top-level segment array ("s")
                "c": 1 // comparator, possible values: 0 -> IS IN SEGMENT, 1 -> IS NOT IN SEGMENT
              }
            }
          ],
          "s": { // alternatively, an array of Percentage Options ("p", see below) can also be specified
            "v": { // the value served when the rule is selected during evaluation
              "b": true
            },
            "i": "bcfb84a7"
          }
        }
      ],
      "p": [ // array of Percentage Options
        {
          "p": 10, // % value
          "v": { // the value served when the Percentage Option is selected during evaluation
            "b": true
          },
          "i": "bcfb84a7"
        },
        {
          "p": 90,
          "v": {
            "b": false
          },
          "i": "bddac6ae"
        }
      ],
      "v": { // fallback value, served when none of the Targeting Rules match,
             // no Percentage Options are defined or evaluation of these is not possible
        "b": false // depending on the setting type, another type of value may need to be specified:
                   // text setting -> "s": string
                   // whole number setting -> "i": number
                   // decimal number setting -> "d": number
      },
      "i": "430bded3" // variation id (for analytical purposes)
    }
  }
}

```

For a more comprehensive specification of the config JSON v6 format, you may refer to [this JSON schema document](https://github.com/configcat/config-json/blob/main/V6/config.schema.json).

### Map[​](#map "Direct link to Map")

You can set up the SDK to load your feature flag & setting overrides from a map.

```cpp
const std::unordered_map<std::string, Value>& map = {
    { "enabledFeature", true },
    { "disabledFeature", false },
    { "intSetting", 5 },
    { "doubleSetting", 3.14 },
    { "stringSetting", "test" }
};

ConfigCatOptions options;
options.flagOverrides = std::make_shared<MapFlagOverrides>(map, LocalOnly);
auto client = ConfigCatClient::get("#YOUR-SDK-KEY#", &options);

```

## `getAllKeys()`[​](#getallkeys "Direct link to getallkeys")

You can get the keys for all available feature flags and settings by calling the `getAllKeys()` method.

```cpp
auto client = ConfigCatClient::get("#YOUR-SDK-KEY#");
auto keys = client->getAllKeys();

```

## `getAllValues()`[​](#getallvalues "Direct link to getallvalues")

Evaluates and returns the values of all feature flags and settings. Passing a User Object is optional.

```cpp
auto client = ConfigCatClient::get("#YOUR-SDK-KEY#");
auto settingValues = client->getAllValues();

// invoke with User Object
auto user = ConfigCatUser::create("#UNIQUE-USER-IDENTIFIER#");
auto settingValuesTargeting = client->getAllValues(user);

```

## `getAllValueDetails`[​](#getallvaluedetails "Direct link to getallvaluedetails")

Evaluates and returns the detailed values of all feature flags and settings. Passing a [User Object](#user-object) is optional.

```cpp
auto client = ConfigCatClient::get("#YOUR-SDK-KEY#");

// invoke with User Object
auto user = ConfigCatUser::create("#UNIQUE-USER-IDENTIFIER#");
auto allValueDetails = client->getAllValueDetails(user)

```

## Custom Cache[​](#custom-cache "Direct link to Custom Cache")

The *ConfigCat SDK* stores the downloaded config data in a local cache to minimize network traffic and enhance client performance. If you prefer to use your own cache solution, such as an external or distributed cache in your system, you can implement the [`ConfigCache`](https://github.com/configcat/cpp-sdk/blob/main/include/configcat/configcache.h#L8) interface and set the `configCache` parameter in the options passed to `ConfigCatClient::get`. This allows you to seamlessly integrate ConfigCat with your existing caching infrastructure.

You have the option to inject your custom cache implementation into the client. All you have to do is to inherit from the `ConfigCatCache` abstract class:

```cpp
class MyCustomCache : public ConfigCatCache {
public:
    const std::string& read(const std::string& key) override {
        // here you have to return with the cached value
    }

    void write(const std::string& key, const std::string& value) override {
        // here you have to store the new value in the cache
    }
};

```

Then use your custom cache implementation:

```cpp
ConfigCatOptions options;
options.configCache = std::make_shared<MyCustomCache>();
auto client = ConfigCatClient::get("#YOUR-SDK-KEY#", &options);

```

info

The C++ SDK supports *shared caching*. You can read more about this feature and the required minimum SDK versions [here](https://configcat.com/docs/advanced/caching.md#shared-cache).

## Force refresh[​](#force-refresh "Direct link to Force refresh")

Call the `forceRefresh()` method on the client to download the latest config JSON and update the cache.

## Using ConfigCat behind a proxy[​](#using-configcat-behind-a-proxy "Direct link to Using ConfigCat behind a proxy")

Provide your own network credentials (username/password), and proxy server settings (proxy server/port) in the `ConfigCatOptions`.

```cpp
ConfigCatOptions options;
options.proxies = {{"https", "proxyhost:port"}}; // Protocol, Proxy
options.proxyAuthentications = {
    {"https", ProxyAuthentication{"user", "password"}} // Protocol, ProxyAuthentication
};
auto client = ConfigCatClient::get("#YOUR-SDK-KEY#", &options);

```

## Changing the default HTTP timeout[​](#changing-the-default-http-timeout "Direct link to Changing the default HTTP timeout")

Set the maximum wait time for a ConfigCat HTTP response by changing the *connectTimeoutMs* or *readTimeoutMs* in the `ConfigCatOptions`. The default *connectTimeoutMs* is 8 seconds. The default *readTimeoutMs* is 5 seconds.

```cpp
ConfigCatOptions options;
options.connectTimeoutMs = 10000; // Timeout in milliseconds for establishing a HTTP connection with the server
options.readTimeoutMs = 8000; // Timeout in milliseconds for reading the server's HTTP response
auto client = ConfigCatClient::get("#YOUR-SDK-KEY#", &options);

```

## Logging[​](#logging "Direct link to Logging")

### Setting log levels[​](#setting-log-levels "Direct link to Setting log levels")

```cpp
#include <configcat/configcat.h>
#include <configcat/consolelogger.h>

auto logger = std::make_shared<ConsoleLogger>(LOG_LEVEL_WARNING);
ConfigCatOptions options;
options.logger = logger;
auto client = ConfigCatClient::get("#YOUR-SDK-KEY#", &options);

```

You can change the verbosity of the logs by setting the `LogLevel`.

```cpp
logger->setLogLevel(LOG_LEVEL_INFO);

```

Available log levels:

| Level               | Description                                                                             |
| ------------------- | --------------------------------------------------------------------------------------- |
| `LOG_LEVEL_ERROR`   | Only error level events are logged.                                                     |
| `LOG_LEVEL_WARNING` | Default. Errors and Warnings are logged.                                                |
| `LOG_LEVEL_INFO`    | Errors, Warnings and feature flag evaluation is logged.                                 |
| `LOG_LEVEL_DEBUG`   | All of the above plus debug info is logged. Debug logs can be different for other SDKs. |

Info level logging helps to inspect how a feature flag was evaluated:

```bash
[INFO]:[5000] Evaluating 'isPOCFeatureEnabled' for User '{"Identifier":"<SOME USERID>","Email":"configcat@example.com","Country":"US","SubscriptionType":"Pro","Role":"Admin","version":"1.0.0"}'
  Evaluating targeting rules and applying the first match if any:
  - IF User.Email CONTAINS ANY OF ['@something.com'] THEN 'false' => no match
  - IF User.Email CONTAINS ANY OF ['@example.com'] THEN 'true' => MATCH, applying rule
  Returning 'true'.

```

### Custom logger implementation[​](#custom-logger-implementation "Direct link to Custom logger implementation")

In the ConfigCat SDK, the default logger (`ConsoleLogger`) writes logs to the standard output, but you can override it with your implementation via the `logger` client option. The custom logger must implement the `ILogger` abstract class.

```cpp
#include "log.h"

class CustomLogger : public ILogger {
public:
    void log(LogLevel level, const std::string& message, const std::exception_ptr& exception) override {
        // Write the logs
        std::cout << logLevelAsString(level) << ": " << message << std::endl;
        if (exception) {
            std::cout << "Exception details: " << unwrap_exception_message(exception) << std::endl;
        }
    }
};

```

```cpp
auto logger = std::make_shared<CustomLogger>();
logger->setLogLevel(LOG_LEVEL_INFO);

ConfigCatOptions options;
options.logger = logger;
auto client = ConfigCatClient::get("#YOUR-SDK-KEY#", &options);

```

## Sensitive information handling[​](#sensitive-information-handling "Direct link to Sensitive information handling")

The frontend/mobile SDKs are running in your users' browsers/devices. The SDK is downloading a [config JSON](https://configcat.com/docs/requests.md) file from ConfigCat's CDN servers. The URL path for this config JSON file contains your SDK key, so the SDK key and the content of your config JSON file (feature flag keys, feature flag values, Targeting Rules, % rules) can be visible to your users. In ConfigCat, all SDK keys are read-only. They only allow downloading your config JSON files, but nobody can make any changes with them in your ConfigCat account.

If you do not want to expose the SDK key or the content of the config JSON file, we recommend using the SDK in your backend components only. You can always create a backend endpoint using the ConfigCat SDK that can evaluate feature flags for a specific user, and call that backend endpoint from your frontend/mobile applications.

Also, we recommend using [confidential targeting comparators](https://configcat.com/docs/targeting/targeting-rule/user-condition.md#confidential-text-comparators) in the Targeting Rules of those feature flags that are used in the frontend/mobile SDKs.

## Sample Applications[​](#sample-applications "Direct link to Sample Applications")

Check out our Sample Application how they use the ConfigCat SDK

* [ConfigCat C++ Console Sample App](https://github.com/configcat/cpp-sdk/tree/main/samples/)

## Guides[​](#guides "Direct link to Guides")

See [this](https://configcat.com/blog/2022/10/21/configcat-cpp-sdk-announcement/) guide on how to use ConfigCat's C++ SDK.

## Look Under the Hood[​](#look-under-the-hood "Direct link to Look Under the Hood")

* [ConfigCat C++ SDK's repository on GitHub](https://github.com/configcat/cpp-sdk)